在 CMake 中,如何找到包含文件的目录? [英] In CMake, how can I find the directory of an included file?
问题描述
假设我的项目的 CMakeLists.txt
包含 foo.cmake
:
Suppose my project's CMakeLists.txt
includes foo.cmake
:
include(foo)
在foo.cmake
中,我想知道foo.cmake
的路径.
我该怎么做?
In foo.cmake
, i want to know the path of foo.cmake
.
How can I do that?
请注意,CMAKE_CURRENT_LIST_DIR
给出了包含 CMakeLists.txt
的目录,而不是包含的 foo.cmake
的目录,因此不是我想要什么.
Note that CMAKE_CURRENT_LIST_DIR
gives the directory of the including CMakeLists.txt
, not that of the included foo.cmake
, and is thus not what I want.
当然,foo.cmake
可能包含在多个项目中(即,包含在多个 CMakeLists.txt
文件中).
Of course, foo.cmake
might be included by several projects (i.e., by several CMakeLists.txt
files).
推荐答案
人们已经报告了关于 CMAKE_CURRENT_LIST_DIR 行为的看似矛盾的事实.现在我知道混乱的原因了:
People have reported seemingly contradictory facts about how CMAKE_CURRENT_LIST_DIR behaves. Now I know the reason for the confusion:
首先,在我的 Linux 环境中:
First, in my Linux environment:
$ cd /path/to/home
$ mkdir cmake-test
$ cd cmake-test
$ mkdir source
$ mkdir source/subdirectory
$ mkdir build
我创建了这两个文件:
$ cat source/CMakeLists.txt
include(subdirectory/foo.cmake)
$ cat source/subdirectory/foo.cmake
message("CMAKE_CURRENT_LIST_DIR is ${CMAKE_CURRENT_LIST_DIR}")
CMake 的工作原理由 Fraser 和 Robert Dailey 报告:
CMake works as reported by Fraser and Robert Dailey:
$ cd build
$ cmake ../source
CMAKE_CURRENT_LIST_DIR is /path/to/home/cmake-test/source/subdirectory
[...]
但是,我向 foo.cmake 添加了一个函数,该函数是从 CMakeLists.txt 调用的:
However, I add a function to foo.cmake, which I call from CMakeLists.txt:
$ cat ../source/subdirectory/foo.cmake
message("CMAKE_CURRENT_LIST_DIR is ${CMAKE_CURRENT_LIST_DIR}")
function(bar)
message("CMAKE_CURRENT_LIST_DIR in bar() is ${CMAKE_CURRENT_LIST_DIR}")
endfunction()
$ cat ../source/CMakeLists.txt
include(subdirectory/foo.cmake)
bar()
那么:
$ cmake ../source
CMAKE_CURRENT_LIST_DIR is /path/to/home/cmake-test/source/subdirectory
CMAKE_CURRENT_LIST_DIR in bar() is /path/to/home/cmake-test/source
[...]
因此,foo.cmake 中 CMAKE_CURRENT_LIST_DIR 的值在包含 foo.cmake 和调用 bar() 时并不相同.这是根据 CMAKE_CURRENT_LIST_DIR 的规范.
So, the value of CMAKE_CURRENT_LIST_DIR in foo.cmake is not the same at the time foo.cmake is included and when bar() is called. This is according to the specification of CMAKE_CURRENT_LIST_DIR.
这是从 bar() 中访问 foo.cmake 目录的一种可能的解决方案:
Here is one possible solution for accessing the directory of foo.cmake from within bar():
$ cat ../source/subdirectory/foo.cmake
set(DIR_OF_FOO_CMAKE ${CMAKE_CURRENT_LIST_DIR})
function(bar)
message("DIR_OF_FOO_CMAKE in bar() is ${DIR_OF_FOO_CMAKE}")
endfunction()
之后我得到了我正在寻找的行为:
after which I get the behavior I was looking for:
$ cmake ../source
DIR_OF_FOO_CMAKE in bar() is /path/to/home/cmake-test/source/subdirectory
[...]
这篇关于在 CMake 中,如何找到包含文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!