0

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
1
  • Yes you can using wildcards. But please always put what you have tried yourself. Commented Feb 28, 2020 at 8:51

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Botje! However, after compiling with make successfully, I cannot find the binary of the sample1. Do you have any idea?
The EXCLUDE_FROM_ALL option prevents your samples from building by default. You can make samples or make sample1, or just remove the EXCLUDE_FROM_ALL if you always want to build samples.
Thanks a lot for your help! I appreciate that.
Btw, if there are many samples directories, e.g. 50 directories. How can I have a loop for each directory such as add_executable(${samplename} samples/${samplename}/main.cpp)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.