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



根据 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 已按预期传播,则第二个编译指示输出将更改为“一条消息!”案件。为什么这不发生?

最佳答案

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

如果你想选择这些设置,你需要在递归到子目录之前设置它们。

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

10-07 12:30
查看更多