CMAKE-自定义目标

CMAKE-自定义目标,c,build,cmake,C,Build,Cmake,我想为构建目的制定几个目标。我有一个项目结构 src - library in c test -test code for lib example -example code for lib 我想使用 cmake make lib make test make example 这可能吗?我尝试使用自定义目标,但无法仅使用/–每个目标将创建一个make目标 通常,项目根目录中有一个CMakeLists.txt(=根文件),每个源目录中有一个。这将为您提供一个漂亮且干净的项目结构 这听起来比实

我想为构建目的制定几个目标。我有一个项目结构

src
- library in c
test
-test code for lib
example
-example code for lib
我想使用

cmake 
make lib
make test
make example
这可能吗?我尝试使用自定义目标,但无法

仅使用/–每个目标将创建一个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
src/CMakeLists.txt test/CMakeList.txt 注意:目标
测试是保留的,将运行您的测试(ctest)

示例/CMakeLists.txt
用法 与其从项目根目录运行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几乎可以做任何事情

保健

CMake不仅用于生成makefile,还可以生成其他构建类型。可能有一种方法可以将自定义目标添加到makefile中,但这不是一个好主意。相反,您可以通过标志控制cmake中特定目标的生成。
我尝试使用自定义目标,但无法
-向我们展示您到底尝试了什么。构建库/可执行文件是CMake的一项基本内容,几乎所有教程都会对此进行描述。调整目标之间的依赖关系也是如此。
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)
mkdir build && cd build
cmake ..
make # Will build all targets (you can also do make example etc).
make tests
make example1
make example1
make lib
# ...