如何在不同的CMakeList.txt之间共享变量?

How to share variables between different CMakeList.txt?

本文关键字:txt 之间 共享变量 CMakeList      更新时间:2023-10-16

我有一个有多个CMakeList.txt的项目,一个用于代码,一个用于单元测试,另外两个用于库,我想分享一些CMakeList.txt行以避免重复,例如:

cmake_minimum_required(VERSION 3.0)set(CMAKE_CXX_STANDARD 17)

我可以使用类似include("MyProject/CMakeConfig.txt")的东西吗?

通常,您有一个 CMake 列表文件位于项目的顶层,另一个用作子目录。由于项目需要一次cmake_minimum_requiredproject,因此您应该可以不写任何内容。

下面是一个结构示例:

顶级./CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(my-project CXX)
# set global property for all this file and subdirectories
set(CMAKE_CXX_STANDARD 17)
# needs to be at the top level
enable_testing()
add_subdirectory(src)
add_subdirectory(test)

src/CMakeLists.txt

add_executable(your-exec file1.cpp file2.cpp file3.cpp)
add_library(your-lib file4.cpp file5.cpp file6.cpp)
find_package(liba REQUIRED)
target_link_libraries(your-exec PUBLIC liba::liba)
target_include_directory(...)
# ...

test/CMakeLists.txt

find_package(Catch2 REQUIRED)
add_executable(test1 test1.cpp)
# link into you lib and a test framework
target_link_libraries(test1 PRIVATE your-lib Catch2::Catch2) 
add_test(NAME test1 COMMAND test1)

所有添加的子目录都将继承项目的基本属性,例如最低 CMake 版本、启用的语言和显式设置的基于目录的属性,例如CMAKE_CXX_STANDARD

综上所述,添加 C++17 作为使用项目的要求总是一个好主意:

# All users of your-lib need C++17
target_compile_features(your-lib PUBLIC cxx_std_17)