我的项目使用相同的核心代码,我想构建以下结构
project
|
| - core_code
| - cmake
| - CMakeLists.txt
| - example1
| |
| |- example1.cc
| |- build
|
| - example2
| |
| |- example2.cc
| |- build
我希望cmake在每个示例的build子目录中创建目标。所以在我从cmake
目录运行projects
然后构建之后,结构应如下所示:
project
|
| - core
| - cmake
| - CMakeLists.txt
| - example1
| |
| |- example1.cc
| |- build
| |- Makefile
| |- example1
|
| - example2
| |
| |- example2.cc
| |- build
| |- Makefile
| |- example2
我应该在project/CMakeLists.txt
做什么?
答案 0 :(得分:1)
如果您按如下方式构建项目:
project
|
|- CMakeLists.txt
|- core
| |
| |- core.cc
| |- core.h
| |- CMakeLists.txt
|
|- example1
| |
| |- example1.cc
| |- CMakeLists.txt
|
|- example2
|
|- example2.cc
|- CMakeLists.txt
您的project/CMakeLists.txt
文件只包含其他cmakelists文件
<强> project/CMakeLists.txt
强>
cmake_minimum_required (VERSION 3.5)
project (project CXX C)
add_subdirectory(core)
add_subdirectory(example1)
add_subdirectory(example2)
您的core/CMakeLists.txt
文件构建核心目标
<强> project/core/CMakeLists.txt
强>
add_library(core core.cc)
target_include_directories(core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
您的exampleN/CMakeLists.txt
文件会构建示例目标
<强> project/example1/CMakeLists.txt
强>
add_executable(example1 example.cc)
target_link_libraries(example1 core)
生成构建文件时,cmake会在构建目录中模仿目录结构,因此运行以下命令将导致以下目录结构:
$ cd project
$ mkdir build
$ cd build
$ cmake ..
生成的目录结构如下所示:
project
|
|- CMakeLists.txt
|- core
| |
| |- core.cc
| |- core.h
| |- CMakeLists.txt
|
|- example1
| |
| |- example1.cc
| |- CMakeLists.txt
|
|- example2
| |
| |- example2.cc
| |- CMakeLists.txt
|
|- build
|
|- Makefile
|- core
| |- Makefile
|
|- example1
| |- Makefile
| |- example1
|
|- example2
|- Makefile
|- example2
现在,如果您只想构建example2
,则可以执行以下操作:
$ cd project/build/example2
$ make
这样做的好处是它不会使用构建文件污染源树。如果你想要删除构建目录,你只需要删除一个目录
$ rm -r project/build
答案 1 :(得分:0)
假设您某处有附加 CMakeLists.txt
,例如在cmake/example/CMakeLists.txt
,内容如下:
add_executable(${EXAMPLE_NAME} ${EXAMPLE_DIR}/${EXAMPLE_NAME}.cc)
您可以通过以下方式从project/CMakeLists.txt
拨打电话:
# Build the first example in the 'example1/build' subdirectory
set(EXAMPLE_NAME example1)
set(EXAMPLE_DIR ${CMAKE_SOURCE_DIR}/example1)
add_subdirectory(cmake/example ${CMAKE_SOURCE_DIR}/example1/build)
# Build the second example in the 'example2/build' subdirectory
set(EXAMPLE_NAME example2)
set(EXAMPLE_DIR ${CMAKE_SOURCE_DIR}/example2)
add_subdirectory(cmake/example ${CMAKE_SOURCE_DIR}/example2/build)
请注意,CMake仅在构建目录中生成Makefile,并且更改构建目录的唯一方法是add_subdirectory()
调用。因此,如果没有其他Makefile
,则无法将CMakeLists.txt
放在顶级目录中。但是您可以为多个构建目录使用单个附加CMakeLists.txt
。
准确地说,您可能也可以使用顶级CMakeLists.txt
作为示例,但您需要将其设为&#34; reentrant&#34;,这对我来说似乎很难看。