我有一个定义函数的CMakeLists.txt,需要引用它自己的路径,因为它需要在自己的目录中使用一个文件:
├── path/to/a:
| ├── CMakeLists.txt
| └── file_i_need.in
└── different/path/here:
└── CMakeLists.txt
path/to/a/CMakeLists.txt
文件的功能需要configure_file()
:
function(do_something_interesting ...)
configure_file(
file_i_need.in ## <== how do I get the path to this file
file_out ## <== this one I don't need to path
)
endfunction()
我可以在那条线上写path/to/a/file_i_need.in
,但这看起来过于繁琐。我可以在函数外部使用${CMAKE_CURRENT_LIST_DIR}
,但在different/path/here/CMakeLists.txt
调用函数内部时,它将是different/path/here
。
有没有办法引用这个 CMakeLists.txt的路径?
答案 0 :(得分:3)
在 CMAKE_CURRENT_LIST_DIR 的任何函数存储值之外的变量中,然后在该文件中定义的函数中使用该变量。
变量的定义取决于定义函数( define-script )的脚本和可以使用该函数的脚本( use-script )。
use-script 在 define-script 的范围内执行。
这是最常见的情况, use-script 包含在 define-script 或其中一个父项中。
变量可以定义为一个简单的变量:
set(_my_dir ${CMAKE_CURRENT_LIST_DIR})
use-script 执行超出 define-script 的范围。请注意,函数的定义是 global ,因此它在任何地方都可见。
此案例与问题帖子中的代码相对应,其中CMakeLists.txt
文件对应使用脚本,定义脚本属于不同的子树。
该变量可以定义为 CACHE 变量:
set(_my_dir ${CMAKE_CURRENT_LIST_DIR} CACHE INTERNAL "")
在两种情况下,函数定义都是相同的:
function(do_something_interesting ...)
configure_file(
${_my_dir}/file_i_need.in ## <== Path to the file in current CMake script
file_out ## <== this one I don't need to path
)
endfunction()
在这两种情况下,变量(_my_dir
)的名称应该是某种独特的。它可以包含项目的名称(对于脚本CMakeLists.txt
)或脚本名称(对于脚本<name>.cmake
)。
答案 1 :(得分:1)
作为更新,自release CMake 3.17起,您现在可以使用CMAKE_CURRENT_FUNCTION_LIST_DIR
。
参考:https://cmake.org/cmake/help/v3.17/variable/CMAKE_CURRENT_FUNCTION_LIST_DIR.html
因此您的样本变为:
function(do_something_interesting ...)
configure_file(
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/file_i_need.in ## <== Path to the file in current CMake script
file_out ## <== this one I don't need to path
)
endfunction()