在函数中使用 CMAKE_CURRENT_LIST_DIR

Bar*_*rry 5 cmake

我有一个定义函数的 CMakeLists.txt,它需要引用自己的路径,因为它需要使用自己目录中的文件:

??? path/to/a:
|   ??? CMakeLists.txt
|   ??? file_i_need.in
??? different/path/here:
    ??? CMakeLists.txt
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

我可以写path/to/a/file_i_need.in在那条线上,但这似乎过于繁琐。我可以${CMAKE_CURRENT_LIST_DIR}在函数外部使用,但在函数内部调用时different/path/here/CMakeLists.txtdifferent/path/here改为使用。

有没有办法引用这个CMakeLists.txt的路径?

Tsy*_*rev 5

在任何函数之外,将CMAKE_CURRENT_LIST_DIR 的值存储到一个变量中,然后在该文件中定义的函数中使用该变量。

变量的定义取决于定义函数 ( define-script ) 的脚本和可以使用该函数的脚本( use-script )之间的可见性关系。

  1. 使用脚本执行中的范围限定,脚本

    这是最常见的情况,当use-script包含在define-script或其父项之一中时。

    变量可以定义为一个简单的变量:

    set(_my_dir ${CMAKE_CURRENT_LIST_DIR})
    
    Run Code Online (Sandbox Code Playgroud)
  2. use-scriptdefine-script的范围之外执行。请注意,函数的定义是global,因此它在任何地方都可见。

    本例对应题帖中的代码,其中CMakeLists.txt文件,分别对应use-scriptdefine-script,属于不同的子树

    该变量可以定义为一个CACHE变量:

    set(_my_dir ${CMAKE_CURRENT_LIST_DIR} CACHE INTERNAL "")
    
    Run Code Online (Sandbox Code Playgroud)

两种情况下的函数定义相同:

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()
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,变量 ( _my_dir) 的名称都应该是唯一的。它可以包括项目名称(对于 scripts CMakeLists.txt)或脚本名称(对于 scripts <name>.cmake)。