2

What I want to do is to create a CMakeLists.txt that defines a convenience macro to use in parent scope. I can use the macro just fine. However, I used the ${CMAKE_CURRENT_SOURCE_DIR} which is unfortunately not the directory of the CMake script the macro is defined in, but the one it is called from. Is there any way I can change that?

MWE

cmake_minimum_required(VERSION 3.6)
project(git_info CXX)
macro(do_stuff)
    message("This CMakeLists.txt file is in ${CMAKE_CURRENT_SOURCE_DIR}")
endmacro()

One ugly way I found was to export variables to the parent scope that contain the path and use that in the macro. But I would prefer to only export the macro definition, if possible, to keep things clean.

Edit: To clarify a bit. I have one folder with my top-levelCMakeLists.txt and one folder (my_folder) inside with the above MWE CMakeLists.txt. The top-level CMakeLists.txt looks as follows:

cmake_minimum_required(VERSION 3.6)
project(top_project CXX)
add_subdirectory(my_folder)
do_stuff()
NOhs
  • 2,780
  • 3
  • 25
  • 59

2 Answers2

2

You have to transfer CMAKE_CURRENT_LIST_DIR outside the macro into another variable or - in your case - a user defined global property:

set_property(GLOBAL PROPERTY DoStuffPath "${CMAKE_CURRENT_LIST_DIR}")

macro(do_stuff)
    get_property(_my_marcros_file GLOBAL PROPERTY DoStuffPath)
    message("This CMakeLists.txt file is in ${_my_marcros_file}")
endmacro()

That also works when the macros are defined in a file added with include().

References

Community
  • 1
  • 1
Florian
  • 39,996
  • 9
  • 133
  • 149
  • This has the issue, that, since the macro is called in parent_scope, `_my_marcros_file` is invisible to the place where the macro is defined. Thus the printed message will be ("This CMakeLists.txt file is in "). – NOhs Mar 13 '17 at 09:10
  • I added some clarification to the question. – NOhs Mar 13 '17 at 09:15
  • But it is the other way around. I want to use the macro defined in the child scope in parent scope. Which works, but I don't want to make the variables of the child scope visible to the parent scope. – NOhs Mar 13 '17 at 09:19
  • @MrZ Ok. I've just see your changed question. Modified my code to work in your scenario also by using a user defined global property. – Florian Mar 13 '17 at 09:21
-1

Use CMAKE_SOURCE_DIR to get a path to outermost parent CMakeLists.txt.

dragn
  • 1,030
  • 1
  • 8
  • 21