【问题标题】:How to write a CMakeLists.txt to build some source code and its sample code?如何编写 CMakeLists.txt 来构建一些源代码及其示例代码?
【发布时间】:2020-06-12 08:16:24
【问题描述】:

有几个 C++ 源代码不使用 CMake 作为构建系统。假设我有这样一个文件结构:

ProjectRepoDir
  |- include
     |- liba.h
     |- module1.h
  |- src
     |- main.cpp
     |- liba.cpp
     |- module1.cpp
  |- samples
     |- example1-dir
        |- main.cpp
     |- example2-dir
        |- main.cpp

我可以在ProjectRepoDir 下创建一个 CMakeLists.txt,并在该目录中执行这些命令来构建源代码和所有示例目录吗?原因是我不想在每个samples目录下都写CMakeLists.txt。

mkdir build && cd build
cmake ..
make

【问题讨论】:

  • 是的,您可以使用通配符。但请始终把你自己尝试过的东西放上去。

标签: c++ cmake


【解决方案1】:

当然,您可以从顶级 CMakeLists.txt 执行所有操作:

# Extract the common parts in a (internal) static library
add_library(liba STATIC src/liba.cpp src/module1.cpp)
target_include_directories(liba PUBLIC include)

add_executable(my-project src/main.cpp)
target_link_libraries(my-project liba)

# Add a `samples` target that enables building the sample programs
# Not built by default.
add_executable(sample1 EXCLUDE_FROM_ALL samples/example1-dir/main.cpp)
target_link_libraries(sample1 liba)

add_executable(sample2 EXCLUDE_FROM_ALL samples/example2-dir/main.cpp)
target_link_libraries(sample2 liba)

add_custom_target(samples DEPENDS sample1 sample2)

【讨论】:

  • 谢谢博杰!但是,使用make 编译成功后,我找不到sample1 的二进制文件。你有什么想法吗?
  • EXCLUDE_FROM_ALL 选项默认阻止您的样本构建。您可以make samplesmake sample1,或者如果您总是想构建示例,则只需删除EXCLUDE_FROM_ALL
  • 非常感谢您的帮助!我很感激。
  • 顺便说一句,如果有很多示例目录,例如50 个目录。如何为每个目录创建一个循环,例如add_executable(${samplename} samples/${samplename}/main.cpp)
猜你喜欢
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-25
  • 2010-11-17
相关资源
最近更新 更多