How to define a cmake macro in a sub_directory tha

2019-02-28 17:41发布

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

标签: cmake
2条回答
【Aperson】
2楼-- · 2019-02-28 17:55

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

查看更多
放荡不羁爱自由
3楼-- · 2019-02-28 18:01

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

查看更多
登录 后发表回答