检查cmake中目标顺序不正确的目标 [英] Check for optionally targets in cmake that are not in the correct order
问题描述
我目前正在从事一个大型软件项目,该项目使用cmake作为构建系统。但是我有一个问题要检查是否存在另一个目标(或将要存在)。
i'm currently working on a large software project which uses cmake as build system. But i have a problem to check if another target exists (or will exist).
例如,有CMakeLists.txt根目录和两个可以选择性地添加到软件中的模块项目作为子文件夹。
For example there is root CMakeLists.txt and two modules that can optionally added to the software project as subfolders.
.
├── A
│ └── CMakeLists.txt
├── B
│ └── CMakeLists.txt
└── CMakeLists.txt
在根CMakeList中,这些模块通过add_subdirectory命令添加:
In the root CMakeLists these modules are added with the add_subdirectory command:
cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR)
project(root)
add_subdirectory(./A)
add_subdirectory(./B)
在某些情况下,我想在模块A中检查模块B是否存在,并将定义添加到编译中模块A中的选项:
In some cases i want to check in module A if module B exists and add an define to the compile options in module A:
cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR)
project(A)
add_libary(A a.cpp a.hpp)
if (TARGET B)
target_compile_definitions(A PUBLIC HAVE_B)
endif()
The
if(TARGET target-name)
命令将返回false,因为只有将模块以正确的顺序添加到根CMakeLists.txt时,此命令才起作用。
command will return false because this will only work if the modules are added in the right order to the root CMakeLists.txt.
是重新进行一次不取决于目标顺序的检查吗?
Is there another check in cmake that doesn't depend on the order of the targets?
问候
Perry
Greetings Perry
推荐答案
由于根 CMakeLists.txt
文件必须知道项目的子目录,因此我通常在此处放置可选设置:
Because the root CMakeLists.txt
file have to know the project's subdirectories, I normally put my optional settings there:
CMakeLists.txt :
cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR)
project(root CXX)
if (EXISTS "B/CMakeLists.txt")
set(HAVE_B 1)
endif()
add_subdirectory(A)
if (HAVE_B)
add_subdirectory(B)
endif()
A / CMakeLists.txt :
add_library(A a.cpp a.hpp)
if (HAVE_B)
target_link_libraries(A B)
endif()
B / CMakeLists.txt :
add_library(B b.cpp b.hpp)
target_compile_definitions(B PUBLIC HAVE_B)
target_include_directories(B PUBLIC .)
有很多可能的地方,您可以设置编译器定义和必要的地方包括目录。在此示例中,我选择使用 进行宣传。 target_compile_definitions(... PUBLIC ...)
和 target_include_directories(... PUBLIC ...)
。然后,您只需使用 target_link_libraries( )
和CMake处理其余部分( target_link_libraries()
确实接受正向声明)。
There are a lot of possibile places you could set the compiler definitions and necessary include directories. In this example I've choosen to propagade both with target_compile_definitions(... PUBLIC ...)
and target_include_directories(... PUBLIC ...)
. Then you just have to setup the dependency with target_link_libraries()
and CMake handles the rest (and target_link_libraries()
does accept forward declarations).
这篇关于检查cmake中目标顺序不正确的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!