使用cmake构建多个示例 [英] Build multiple examples with cmake
问题描述
我的项目使用相同的核心代码,我想构建以下结构
My project uses the same core code, and i want to build the following structure
project
|
| - core_code
| - cmake
| - CMakeLists.txt
| - example1
| |
| |- example1.cc
| |- build
|
| - example2
| |
| |- example2.cc
| |- build
我希望cmake在每个示例的build子目录中创建目标。因此,在我从 projects
目录运行 cmake
然后进行构建之后,结构应如下所示:
I would like cmake to create targets in the build subdirectories for each example. So after I run cmake
from projects
directory then build, the structure should look like this:
project
|
| - core
| - cmake
| - CMakeLists.txt
| - example1
| |
| |- example1.cc
| |- build
| |- Makefile
| |- example1
|
| - example2
| |
| |- example2.cc
| |- build
| |- Makefile
| |- example2
在 project / CMakeLists.txt中我应该怎么做
?
推荐答案
如果您按以下方式构建项目:
If you structure your project as follows:
project
|
|- CMakeLists.txt
|- core
| |
| |- core.cc
| |- core.h
| |- CMakeLists.txt
|
|- example1
| |
| |- example1.cc
| |- CMakeLists.txt
|
|- example2
|
|- example2.cc
|- CMakeLists.txt
您的 project / CMakeLists.txt
文件仅包含其他cmakelists文件
Your project/CMakeLists.txt
file just includes the other cmakelists files
project / CMakeLists .txt
:
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
文件可建立核心目标
Your core/CMakeLists.txt
file builds the core targets
project / core / CMakeLists.txt
:
project/core/CMakeLists.txt
:
add_library(core core.cc)
target_include_directories(core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
您的 exampleN / CMakeLists.txt
文件将建立示例目标
Your exampleN/CMakeLists.txt
file builds the example targets
project / example1 / CMakeLists.txt
:
project/example1/CMakeLists.txt
:
add_executable(example1 example.cc)
target_link_libraries(example1 core)
生成生成文件时,cmake模仿目录结构在build目录中,因此运行以下命令将导致以下目录结构:
When you generate the build files, cmake mimics your directory structure in the build directory, so running the following commands would result in the below directory structure:
$ cd project
$ mkdir build
$ cd build
$ cmake ..
生成的目录结构将会如下所示:
The resulting directory structure would look as follows:
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
,则可以执行以下操作:
Now if you only want to build example2
for example, you can execute the following:
$ cd project/build/example2
$ make
这样做的好处是它不会用构建文件污染您的源代码树。如果要删除构建目录,只需删除一个目录
The benefit of this is that it doesn't pollute your source tree with build files. If you want to blow away the build directory, you only need to delete one directory
$ rm -r project/build
这篇关于使用cmake构建多个示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!