[43998] How to implement different CMake functions with the same name?

Hello,

How can I simply & cleanly implement different functions which share the same name?

Here is a first attempt:

get_extension(MACRO_EXTENSION)
function(get_extension MACRO_EXTENSION)
    set(MACRO_EXTENSION "C" PARENT_SCOPE)
endfunction()

include(${CMAKE_CURRENT_SOURCE_DIR}/../common.cmake)
  • Implementation 2: python/CMakeLists.txt:
function(get_extension MACRO_EXTENSION)
    set(MACRO_EXTENSION "py" PARENT_SCOPE)
endfunction()

include(${CMAKE_CURRENT_SOURCE_DIR}/../common.cmake)

Best Regards,

Salomon

You can’t, CMake only has one scope for functions, and no overloading.

If you need a customisation point for a shared piece of CMake code (as in your case), you must make it a variable, not a function. For a simple case like your example, this could work:

  • common.cmake:
    set(MACRO_EXTENSION ${INJECTED_MACRO_EXTENSION}) # or just use INJECTED_MACRO_EXTENSION directly
    
  • cpp/CMakeLists.txt:
    set(INJECTED_MACRO_EXTENSION C)
    include(common.cmake)
    

For something more complicated, you can inject the name of a command to call:

  • common.cmake:
    cmake_language(CALL ${INJECTED_COMMAND_NAME})
    
  • cpp/CMakeListstxt
    function(cpp_func)
      # whatever
    endfunction()
    set(INJECTED_COMMAND_NAME cpp_func)
    include(common.cmake)
    
  • python/CMakeListstxt
    function(py_func)
      # whatever
    endfunction()
    set(INJECTED_COMMAND_NAME py_func)
    include(common.cmake)
    
1 Like