只需使用 add_executable() / add_library() - 每个目标都会创建一个 make 目标。
通常在项目根目录中有一个CMakeLists.txt(= 根文件),每个源目录中都有一个。这为您提供了一个漂亮而干净的项目结构。
这听起来比实际工作要多……
<<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(项目根目录)
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)
测试/CMakeList.txt
注意:目标test 已保留,将运行您的测试(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)
用法
与其从项目根目录运行 Cmake,不如做一个外源构建:
mkdir build && cd build
cmake ..
make # Will build all targets (you can also do make example etc).
现在生成/本地的所有内容都在build 内,并且项目保持干净。您通常希望将该目录添加到例如。 .gitignore.
按目标构建:
make tests
make example1
make example1
make lib
# ...
您也可以创建一个构建 example1 和 example2 的目标。 CMake 几乎可以做任何事情。
文档