Agus Agus - 11 months ago 64
C Question

CMAKE - Custom Target

I want to make several target for build purpose. I have a project structure

- library in c
-test code for lib
-example code for lib

I want to build using

make lib
make test
make example

Is this possbile? I tried with custom target but I couldn't

Answer Source

Just use add_executable() / add_library() – each target will create a make target.

Typically there's a CMakeLists.txt (= Root file) in the project root and one in each source directory. This gives you a nice & clean project structure.

This sounds more work than it actually is …

<<Project Dir>>
+- CMakeLists.txt
+- src/
|  |
|  +- CMakeLists.txt
|  |
|  +- library in c
+- test/
|  |
|  +- CMakeLists.txt
|  |
|  +- test code for lib
+- example/
   +- CMakeLists.txt
   +- example code for lib

CMakeLists.txt (Project Root)

cmake_minimum_required(VERSION 3.0) # Or what you can use
project(Example VERSION 0.1)

# Add each subdir


add_library(lib Src1.c Src2.c)


Note: The target test is reserved and will run your tests (ctest)

add_executable(tests Test1.c Test2.c)


add_executable(example1 Example1.c)
target_link_libraries(example1 lib)

add_executable(example2 Example2.c)
target_link_libraries(example2 lib)


Instead of running Cmake from project root, better do an out-of-source buid:

mkdir build && cd build
cmake ..
make # Will build all targets (you can also do make example etc).

Now everything generated / local is within build and the proejct stays clean. You typically want to add that directory to eg. .gitignore.

Building per target:

make tests
make example1
make example1
make lib
# ...

You can make a target that builds example1 and example2 too. CMake can do almost everything.