Agus Agus - 2 months ago 17
C Question

CMAKE - Custom Target

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

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


I want to build using

cmake
make lib
make test
make example


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

Answer

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_subdirectory("src")
add_subdirectory("test")
add_subdirectory("example")

src/CMakeLists.txt

add_library(lib Src1.c Src2.c)

test/CMakeList.txt

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

add_executable(tests Test1.c Test2.c)

example/CMakeLists.txt

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

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

Usage

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.

Dokumentation

Comments