gpt4 book ai didi

c++ - 为什么 CMake COMPILER_DEFINITIONS 不传播到子目录?

转载 作者:行者123 更新时间:2023-11-30 03:16:46 26 4
gpt4 key购买 nike

根据 the set_directory_properties docs ,在目录上设置的属性应该传播到子目录:

Set a property for the current directory and subdirectories.

根据 the supported properties documentation , COMPILE_DEFINITIONS 是目录支持的属性。

鉴于此,为什么目录的 COMPILE_DEFINITIONS 不传播到以下示例中的子目录?

示例项目文件结构

- CMakeLists.txt
- sub
-CMakeLists.txt
-main.cpp

文件内容

根 CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.11)
project(cmake_sandbox)
add_subdirectory(sub)
set_directory_properties(PROPERTIES COMPILE_DEFINITIONS SHOW_MESSAGE=1)

子 CMakeLists.txt:

add_executable(hello main.cpp)

主要.cpp:

#include <iostream>
using namespace std;

int main()
{
#define A_LOCAL_MESSAGE
#ifdef A_LOCAL_MESSAGE
#pragma message("A local message!")
#else
#pragma message("No local message!")
#endif

#ifdef SHOW_MESSAGE
#pragma message("A message!")
#else
#pragma message("No message!")
#endif
cout << "Hello, World!\n";
return 0;
}

测试

$ cmake --version
cmake version 3.10.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).
$ rm -rf build && mkdir build && cd build && cmake .. && make -j && sub/hello
-- The C compiler identification is GNU 7.4.0
-- The CXX compiler identification is GNU 7.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/caleb/src/cmake-sandbox/build
Scanning dependencies of target hello
[ 50%] Building CXX object sub/CMakeFiles/hello.dir/main.cpp.o
/home/caleb/src/cmake-sandbox/sub/main.cpp: In function ‘int main()’:
/home/caleb/src/cmake-sandbox/sub/main.cpp:8:36: note: #pragma message: A local message!
#pragma message("A local message!")
^
/home/caleb/src/cmake-sandbox/sub/main.cpp:16:31: note: #pragma message: No message!
#pragma message("No message!")
^
[100%] Linking CXX executable hello
[100%] Built target hello
Hello, World!

如果在根级别设置的 COMPILE_DEFINITION 已按预期传播,则第二个 pragma 输出将更改为“一条消息!”案件。为什么没有发生这种情况?

最佳答案

add_subdirectory 使 CMake 进入子目录并处理其中的 CMakeLists.txt 文件, 处理 add_subdirectory 之后的指令。

如果您想要获取这些设置,您需要在递归到子目录之前设置它们。

set_directory_properties(PROPERTIES COMPILE_DEFINITIONS SHOW_MESSAGE=1)
add_subdirectory(sub)

关于c++ - 为什么 CMake COMPILER_DEFINITIONS 不传播到子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com