Cmake global variable in macro scope

2020-04-23 02:40发布

I'm trying to create a global list and I want it appended in a macro. Here is my setup:

project
\__. CMakeLists.txt
\__. level1
    \__. CMakeLists.txt
    \__. level2a
        \__. CMakeLists.txt
    \__. level2b
        \__. CMakeLists.txt

Here is my top level CMakeLists.txt :

cmake_minimum_required(VERSION 2.8)

macro(listappend var)
    list(APPEND MY_GLOBAL_LIST "${var}")
    message(STATUS "LIST IN MACRO SCOPE: ${MY_GLOBAL_LIST}")
endmacro(listappend)

set(MY_GLOBAL_LIST "")

add_subdirectory(level1)
message(STATUS "LIST: ${MY_GLOBAL_LIST}")

# call something here with the global list

level1 CMakeLists.txt simply do two add_subdirectory().

level2 CMakeLists.txt is as follows:

listappend("test2a")

And finally, here is my output :

[lz@mac 17:15:14] ~/tmp/cmake/build$ cmake ..
-- LIST IN MACRO SCOPE: test2a
-- LIST IN MACRO SCOPE: test2b
-- LIST: 
-- Configuring done
-- Generating done
-- Build files have been written to: /home/lz/tmp/cmake/build

I'm looking for a way to have a Global list appended inside the scope of the macro, without having to give the global list variable as parameter of the macro. I'm not sure if it's possible.

I also tried CACHE INTERNAL flags but it didn't help. I don't really how to handle this.

Thanks for any help :)

1条回答
迷人小祖宗
2楼-- · 2020-04-23 03:12

CMake GLOBAL property is a nice way for implement global list which is modified at different levels:

# Describe property
define_property(GLOBAL PROPERTY MY_GLOBAL_LIST
    BRIEF_DOCS "Global list of elements"
    FULL_DOCS "Global list of elements")
# Initialize property
set_property(GLOBAL PROPERTY MY_GLOBAL_LIST "")

# Macro for add values into the list
macro(listappend var)
    set_property(GLOBAL APPEND PROPERTY MY_GLOBAL_LIST "${var}")
endmacro(listappend)

# Do something
add_subdirectory(level1)

# Read list content
get_property(my_list_content GLOBAL PROPERTY MY_GLOBAL_LIST)
message(STATUS "LIST: ${my_list_content}")
查看更多
登录 后发表回答