11

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()
feelfree
  • 11,175
  • 20
  • 96
  • 167

2 Answers2

10

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.

Antonio
  • 19,451
  • 13
  • 99
  • 197
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Great answer! One recommendation: you should take care that this cached variable has a unique name, or your scripts might interfere with each other – Antonio Mar 08 '18 at 17:34
2

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.

Axel Heider
  • 557
  • 4
  • 14