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
Kevin
  • 16,549
  • 8
  • 60
  • 74
ywiyogo
  • 738
  • 2
  • 7
  • 21

1 Answers1

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)
Botje
  • 26,269
  • 3
  • 31
  • 41
  • Thanks Botje! However, after compiling with `make` successfully, I cannot find the binary of the sample1. Do you have any idea? – ywiyogo Feb 28 '20 at 09:31
  • 2
    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. – Botje Feb 28 '20 at 09:36
  • Thanks a lot for your help! I appreciate that. – ywiyogo Feb 28 '20 at 09:44
  • 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)`? – ywiyogo Feb 28 '20 at 09:50
  • See [this answer](https://stackoverflow.com/a/14307434/1548468) – Botje Feb 28 '20 at 09:56