feelfree
feelfree

Reputation: 11753

Can we know the directory where the macro or functions are located in cmake

In CMAKE, it defines the following variables to indicate the directories of files:

CMAKE_CURRENT_LIST_DIR
CMAKE_CURRENT_BINARY_DIR
CMAKE_CURRENT_SOURCE_DIR

They are useful when you process CMake scripts. However, none of them can tell you the directory where MACROs or functions are defined. Give the following example CMakeLists.txt to illustrate my question

project(Hello)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/my_macro.cmake)
test_macro()

Then for the my_macro.cmake, we have definitions for test_macro():

macro(test_macro)
  message("hello")
  #?? Can we know the folder of this macro is located?
  #?? the macro definition file's location
endmacro()

Upvotes: 12

Views: 3712

Answers (2)

Axel Heider
Axel Heider

Reputation: 626

With CMake 3.17 there is CMAKE_CURRENT_FUNCTION_LIST_DIR that can be used in functions, see https://cmake.org/cmake/help/v3.17/variable/CMAKE_CURRENT_FUNCTION_LIST_DIR.html Unfortunately, there is no such thing for macros yet.

Upvotes: 3

I don't think there's an off-the-shelf variable for that, but you could easily make your own:

my_macro.cmake:

set(test_macro__internal_dir ${CMAKE_CURRENT_LIST_DIR} CACHE INTERNAL "")

macro(test_macro)
  message(STATUS "Defined in: ${test_macro__internal_dir}")
endmacro()

The set() line will be processed when the file is included, and the value of CMAKE_CURRENT_LIST_DIR from that processing cached for future use inside the macro.

Upvotes: 10

Related Questions