ywiyogo
ywiyogo

Reputation: 836

How to write a CMakeLists.txt to build some source code and its sample code?

There are several C++ source codes which don't utilize CMake as a build system. Suppose I have such a file structure:

ProjectRepoDir
  |- include
     |- liba.h
     |- module1.h
  |- src
     |- main.cpp
     |- liba.cpp
     |- module1.cpp
  |- samples
     |- example1-dir
        |- main.cpp
     |- example2-dir
        |- main.cpp

Can I create a CMakeLists.txt under the ProjectRepoDir, and in the directory I do these commands to build the source code and all the samples directories? The reason is that I don't want to write CMakeLists.txt in each samples directory.

mkdir build && cd build
cmake ..
make

Upvotes: 0

Views: 238

Answers (1)

Botje
Botje

Reputation: 30830

Sure, you can do everything from the top-level CMakeLists.txt:

# Extract the common parts in a (internal) static library
add_library(liba STATIC src/liba.cpp src/module1.cpp)
target_include_directories(liba PUBLIC include)

add_executable(my-project src/main.cpp)
target_link_libraries(my-project liba)

# Add a `samples` target that enables building the sample programs
# Not built by default.
add_executable(sample1 EXCLUDE_FROM_ALL samples/example1-dir/main.cpp)
target_link_libraries(sample1 liba)

add_executable(sample2 EXCLUDE_FROM_ALL samples/example2-dir/main.cpp)
target_link_libraries(sample2 liba)

add_custom_target(samples DEPENDS sample1 sample2)

Upvotes: 2

Related Questions