cmake父目录和子目录的变量传递
目录树
➜ test_pro6 tree -h
.
├── [1.0K] CMakeLists.txt
├── [4.0K] app_hello
│ ├── [ 794] CMakeLists.txt
│ ├── [ 280] app_hello.c
│ └── [ 218] app_hello.h
├── [ 276] app_main.c
└── [4.0K] build
子目录的cmake
set(TEST_CHILDREN_STR "children str" CACHE INTERNAL "Test Str") # 子cmake 和父cmake都可以访问
set(TEST_CHILDREN_PARENT_SCOPE_STR "children str" PARENT_SCOPE) # 只有父cmake可以访问
# 子cmake 和父cmake都可以访问
set(TEST_CHILDREN_ALL_SCOPE_STR "children str")
set(TEST_CHILDREN_ALL_SCOPE_STR ${TEST_CHILDREN_ALL_SCOPE_STR} PARENT_SCOPE)
message("TEST_PARENT_STR 2:" ${TEST_PARENT_STR})
message("TEST_CHILDREN_STR 2:" ${TEST_CHILDREN_STR})
message("TEST_CHILDREN_PARENT_SCOPE_STR 2:" ${TEST_CHILDREN_PARENT_SCOPE_STR})
message("TEST_CHILDREN_ALL_SCOPE_STR 2:" ${TEST_CHILDREN_ALL_SCOPE_STR})
父目录的cmake
message("TEST_PARENT_STR 1:" ${TEST_PARENT_STR})
message("TEST_CHILDREN_STR 1:" ${TEST_CHILDREN_STR})
message("TEST_CHILDREN_PARENT_SCOPE_STR 1:" ${TEST_CHILDREN_PARENT_SCOPE_STR})
message("TEST_CHILDREN_ALL_SCOPE_STR 1:" ${TEST_CHILDREN_ALL_SCOPE_STR})
add_subdirectory(${APP_HELLO_DIR})#请注意这个位置!!!
message("TEST_PARENT_STR 3:" ${TEST_PARENT_STR})
message("TEST_CHILDREN_STR 3:" ${TEST_CHILDREN_STR})
message("TEST_CHILDREN_PARENT_SCOPE_STR 3:" ${TEST_CHILDREN_PARENT_SCOPE_STR})
message("TEST_CHILDREN_ALL_SCOPE_STR 3:" ${TEST_CHILDREN_ALL_SCOPE_STR})
测试,首次执行cmake ..的结果如下
···
TEST_PARENT_STR 1:parent str
TEST_CHILDREN_STR 1:
TEST_CHILDREN_PARENT_SCOPE_STR 1:
TEST_CHILDREN_ALL_SCOPE_STR 1:
TEST_PARENT_STR 2:parent str
TEST_CHILDREN_STR 2:children str
TEST_CHILDREN_PARENT_SCOPE_STR 2:
TEST_CHILDREN_ALL_SCOPE_STR 2:children str
TEST_PARENT_STR 3:parent str
TEST_CHILDREN_STR 3:children str
TEST_CHILDREN_PARENT_SCOPE_STR 3:children str
TEST_CHILDREN_ALL_SCOPE_STR 3:children str
第二次执行 cmake ..的结果如下
TEST_PARENT_STR 1:parent str
TEST_CHILDREN_STR 1:children str #这一行不同,因为首次执行的时候,还未生成CMakeCache.txt
TEST_CHILDREN_PARENT_SCOPE_STR 1:
TEST_CHILDREN_ALL_SCOPE_STR 1:
TEST_PARENT_STR 2:parent str
TEST_CHILDREN_STR 2:children str
TEST_CHILDREN_PARENT_SCOPE_STR 2:
TEST_CHILDREN_ALL_SCOPE_STR 2:children str
TEST_PARENT_STR 3:parent str
TEST_CHILDREN_STR 3:children str
TEST_CHILDREN_PARENT_SCOPE_STR 3:children str
TEST_CHILDREN_ALL_SCOPE_STR 3:children str
通过以上测试,可以清晰的看到子目录和父目录的变量传递过程,
建议还是将add_subdirectory放在主cmake种较靠上的位置