I have created a project with a subproject in cmake. In the subproject I have a function which wants to access a variable from its defining scope (not the parent project scope).
This is my folder structure:
/project
|-- CMakeLists.txt
'-- /sub
'-- CMakeLists.txt
Outer CMakeLists.txt:
project(mainproject)
cmake_minimum_required(VERSION 3.17)
add_subdirectory(sub)
message("in parent scope: ${V}")
test()
Inner CMakeLists.txt:
project(subproject)
cmake_minimum_required(VERSION 3.17)
set(V "hello")
message("defining scope: ${V}")
function(test)
message("function scope: ${V}")
endfunction()
The output I get:
defining scope: hello
parent scope:
function scope:
-- Configuring done
-- Generating done
My suspicion would be that cmake simply doesn't support closures but then there is this page in the documentation: CMAKE_CURRENT_FUNCTION_LIST_DIR
set(_THIS_MODULE_BASE_DIR "${CMAKE_CURRENT_LIST_DIR}")
function(foo)
configure_file(
"${_THIS_MODULE_BASE_DIR}/some.template.in"
some.output
)
endfunction()
This is almost exactly my use case and exactly what I do but it doesn't work.
What am I missing here?
Note that I could use set(V "hello" PARENT_SCOPE) but I don't want to pollute the parent scope.
Any help appreciated!