Suppose my project's CMakeLists.txt
includes foo.cmake
:
include(foo)
In foo.cmake
, i want to know the path of foo.cmake
.
How can I do that?
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.
Of course, foo.cmake
might be included by several projects (i.e., by several CMakeLists.txt
files).
The
include()
command searches for modules in${CMAKE_MODULE_PATH}
first and then in CMakeModules
dir.So you can just check for file presence with
if(EXISTS ${CMAKE_MODULE_PATH}/foo.cmake)
andif(EXISTS ${CMAKE_ROOT}/Modules/foo.cmake)
.See
CMAKE_CURRENT_LIST_DIR
:Example
I have the following structure:
In my
CMakeLists.txt
:In my
test.cmake
:The result I get when I run CMake from
C:\Work\cmake-test
is:People have reported seemingly contradictory facts about how CMAKE_CURRENT_LIST_DIR behaves. Now I know the reason for the confusion:
First, in my Linux environment:
I create these two files:
CMake works as reported by Fraser and Robert Dailey:
However, I add a function to foo.cmake, which I call from CMakeLists.txt:
Then:
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.
Here is one possible solution for accessing the directory of foo.cmake from within bar():
after which I get the behavior I was looking for: