cmakescopecmake-modules

How can I scope a CMake function so it can't be accessed from outside a file?


I'm trying to write some CMake code in a relatively complex project and I have a module that internally includes another module. The problem is, whenever I include my module, all of the functioned defined in the module it internally includes become available at a global level! This effectively is polluting my global namespace with a bunch of functions I didn't explicitly ask for.

For example:

# 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()

Inside my module:

# 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()

Is there any way inside MyModule.cmake that I can import the functions from AnotherModule.cmake without having them be visible outside of my own module? This other module is written by someone else so I don't have control over it and it includes other functions with very generic names like one called parse_arguments that could potentially cause naming conflicts later on.

Making the functions from AnotherModule.cmake fully invisible outside of MyModule.cmake would be ideal, but even if there were a simple way to just simulate a namespace for the imported functions to be in that would be better than nothing.


Solution

  • In CMake macros and functions has global visibility and nothing can change that.

    Often a function, "internal" to some module, is defined with underscore (_) prefix. Such prefix plays the role of a signal to outer code "not to use me". But this is only a convention, CMake doesn't enforce anything about underscore-prefixed names.

    If including a module has only immediate effects, that is defines custom commands/targets but does not export functions/macros/variables for outer code, you may consider to wrap it with external project (ExternalProject_Add). An external project is a separate CMake project, and none its CMake things like variables or functions are visible outside it.