【问题标题】:Adding the header file folder path in a CMake file在 CMake 文件中添加头文件文件夹路径
【发布时间】:2019-12-04 05:51:28
【问题描述】:

我在我的项目中使用 CMake,构建树结构是这样的 我的系统的树形视图:

tree
.
├─ src
├── CMakeLists.txt
├─ CMakeLists.txt

我有 .cpp 和 .h,它们都存在于 src 文件夹中。所以在更新项目结构时,新的文件夹结构是这样的:

tree
.
├─ src
├── CMakeLists.txt
├─ inc
├── headers
├─── file.h
├─ CMakeLists.txt

现在我将头文件移动到 inc 文件夹并更新 CMakeLists.txt 如下:

include_directories(../inc)
set(HEADERS  ../inc/headerfilename)

add_library(
            libraryName OBJECT
            ${HEADERS}
            application.cpp )


 target_include_directories(libraryName
                            PUBLIC
                            ${CMAKE_CURRENT_SOURCE_DIR}/../inc
                           )

现在在运行 CMake 时出现编译错误:

interrupt.h: No such file or directory
#include "interrupt.h"

可能是什么问题?

编辑: 顶级 CMakeLists.txt 文件包含以下几行。

cmake_minimum_required(VERSION 3.4)
add_subdirectory(src)

【问题讨论】:

  • 您可以尝试打印完整路径吗?在末尾添加这一行:message(Info "Path is ${CMAKE_CURRENT_SOURCE_DIR}/../inc")。为了确保没有发生任何愚蠢的事情,您是否检查过您是否清理了 CMake 缓存?
  • make VERBOSE=1检查路径。
  • 是的,我清除了缓存并在 CMakeLists.txt 中添加了上面的行,它打印为InfoPath is /home/MathFunctions/src/../inc。所以我添加了include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../inc)
  • 最好将 CMakeLists.txt 上移一级。这并不意味着没有其他解决方案,而是更容易使用。
  • @Th. Thielemann:实际上我错过了在问题中添加 CMakeLists.txt。我更新了问题。已经有 CMakeLists.txt 上一级了。

标签: c++ cmake


【解决方案1】:

您可以使用CMAKE_SOURCE_DIR,它指向您的 CMake 源代码树的根。然后,使用target_include_directories() 为您的目标添加每个包含目录。这是您更新的src/CMakeLists.txt 文件:

add_library(libraryName OBJECT
            application.cpp
            )

 target_include_directories(libraryName
                            PUBLIC
                            ${CMAKE_SOURCE_DIR}/inc
                            ${CMAKE_SOURCE_DIR}/inc/folder1
                            ${CMAKE_SOURCE_DIR}/inc/folder2
                            ...
                            )

注意:仅当您希望它们与其他源代码一起出现在 IDE 中时,才需要在 add_library()(使用您的 HEADERS 变量)中添加标头。成功编译不需要此步骤。

【讨论】:

    【解决方案2】:

    更改您的顶级CMakeLists.txt

    cmake_minimum_required(VERSION 3.4)
    include_directories(inc)
    add_subdirectory(src)
    

    【讨论】:

    • 我理解了这个问题,实际上在 inc 文件夹中有一个额外的文件夹导致了问题,现在我也在 include_directories 中添加了该文件夹。但是有什么解决方案可以递归地添加 inc 中的所有目录?
    【解决方案3】:

    将顶级 CMakeLists.txt 更改为

    cmake_minimum_required(VERSION 3.4)
    include_directories(inc/headers)
    add_subdirectory(src)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多