tjw*_*992 1 scope cmake cmake-modules
我正在尝试在一个相对复杂的项目中编写一些 CMake 代码,并且我有一个内部包含另一个模块的模块。问题是,每当我包含我的模块时,它内部包含的模块中定义的所有功能都在全局级别可用!这实际上是用一堆我没有明确要求的函数污染了我的全局命名空间。
例如:
# CMakeLists.txt
# Include my module
include(MyModule)
# Call a function from my module
my_module_function()
# HERE IS THE PROBLEM -- functions from "AnotherModule" are visible here!
# This call works
another_module_function()
Run Code Online (Sandbox Code Playgroud)
在我的模块内:
# MyModule.cmake
# Include another module
# - This other module is written and supported by someone else so I can't modify it
# - No functions from "AnotherModule" will be used outside of "MyModule"
include(AnotherModule)
# Define my function
function(my_module_function)
# Call a function from the other module
another_module_function()
endfunction()
Run Code Online (Sandbox Code Playgroud)
有没有什么方法MyModule.cmake可以让我从中导入函数AnotherModule.cmake而不让它们在我自己的模块之外可见?这个另一个模块是由其他人编写的,所以我无法控制它,它包含其他具有非常通用名称的函数,例如调用的函数parse_arguments,可能会在以后导致命名冲突。
使函数在AnotherModule.cmake外部完全不可见MyModule.cmake是理想的选择,但即使有一种简单的方法来模拟导入函数的命名空间,那也比什么都没有好。
在 CMake 中,宏和函数具有全局可见性,没有什么可以改变这一点。
通常,某个模块的“内部”函数是用下划线 ( _) 前缀定义的。这样的前缀起到了对外代码“不要使用我”的信号的作用。但这只是一个约定,CMake 不会强制执行任何有关下划线前缀名称的操作。
如果包含模块仅具有立竿见影的效果,即定义自定义命令/目标,但不导出外部代码的函数/宏/变量,您可以考虑用外部项目包装它(ExternalProject_Add)。外部项目是一个单独的 CMake 项目,其 CMake 内容(例如变量或函数)在其外部不可见。