I'm writing a CMakeLists.txt to generate files and compile the generated files. I create a function to add some file path strings to a global list variable.
My CMakeLists.txt:
set(source_list "nothing") function(test file_path) list(APPEND source_list ${file_path}) endfunction(test) test(abc.txt) test(def.txt) message("At last, the source_list is:\"${source_list}\"")
The cmake output:
At last, the source_list is:"nothing"
Someone suggested that to use macro instead of function, but I do need use local variable, so I need to use the function instead of macro.
How can I correctly set the global variable source_list in the function test()? Can't cmake do it in a simple and normal way?
You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake . You can unset entries in the Cache with unset(... CACHE) .
Local Variables You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.
Operator to read environment variables. Use the syntax $ENV{VAR} to read environment variable VAR . To test whether an environment variable is defined, use the signature if(DEFINED ENV{<name>}) of the if() command.
The CMake cache may be thought of as a configuration file. The first time CMake is run on a project, it produces a CMakeCache. txt file in the top directory of the build tree. CMake uses this file to store a set of global cache variables, whose values persist across multiple runs within a project build tree.
PARENT_SCOPE is only for parent, it won't work if you have other non-parent script that want to see it as well.
You need cache for the true "global-like" variable. In your case, use:
SET(source_list "${source_list}" CACHE INTERNAL "source_list")
Another approach is to use global properties. Once you set it:
set_property(GLOBAL PROPERTY source_list_property "${source_list}")
you can read it from everywhere:
get_property(source_list GLOBAL PROPERTY source_list_property)
I used in examples above the different names for property (source_list_property
) and for variable (source_list
). Maybe it is better to use the same name. But point is to use a property as global variables, and not about naming.
Such global properties aren't in cache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With