【问题标题】:CMAKE - Custom TargetCMAKE - 自定义目标
【发布时间】:2016-09-06 14:21:41
【问题描述】:

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

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

我想使用

cmake 
make lib
make test
make example

这可能吗?我尝试了自定义目标,但我不能

【问题讨论】:

  • CMake 不仅用于生成 Makefile,它还可以生成其他构建类型。可能有一种方法可以将自定义目标添加到 makefile,但这不是一个好主意。相反,您可以通过标志控制 cmake 中某些目标的生成。
  • I tried with custom target but I couldn't - 告诉我们您究竟尝试了什么。构建库/可执行文件是 CMake 的基本内容,几乎在所有教程中都有描述。调整目标之间的依赖关系也是如此。

标签: c build cmake


【解决方案1】:

只需使用 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
# ...

您也可以创建一个构建 example1example2 的目标。 CMake 几乎可以做任何事情。

文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多