如何使用 CMake 从根文件夹外部添加包含目录

How do I add an include directory from outside the root folder with CMake?

本文关键字:添加 包含目 外部 根文件夹 何使用 CMake      更新时间:2023-10-16

这是我的第一个CMakeLists.txt代码:

#cmake_minimum_required (VERSION 2.6)
project (project)
add_subdirectory(src)
include_directories(${/path_to_directory}/include)

这是子目录中的CMakeList.txt

set (CMAKE_C_FLAGS "-WALL -g")
file(GLOB SRCS *.cpp *.hpp *.h)
add_executable(source ${SRCS})

我仍然无法将path_to_directory包含在我的项目中

编辑:这也不起作用:

file(GLOB mylib *.cpp *.hpp *.h)
add_executable(includeSource ${mystuff})
target_include_directories(
    mystuff
    PUBLIC ${path_to_directory}/include
)

即使问题不清楚,我想你想要target_include_directories(这里是文档(而不是include_directories.

从文档中:

指定编译给定目标时要使用的包含目录或目标。

您可以将其用作:

target_include_directories(
    your_target_name
    PUBLIC ${/path_to_directory}/include
)

根据您的前两个代码,我知道您的可执行文件source无法编译,因为您的编译器找不到${/path_to_directory}/include中的包含文件。

在这个假设下,我可以说你放错了include_directories(${/path_to_directory}/include),它应该在子目录的CMakeList.txt中。

include_directories的文档将帮助您了解:

包含目录将添加到当前 CMakeLists 文件的INCLUDE_DIRECTORIES目录属性中。它们还会添加到当前 CMakeLists 文件中每个目标的 INCLUDE_DIRECTORIES 目标属性中。目标属性值是生成器使用的值。

否则,您可以按照@skypjack的建议,在主 CMakeList 中target_include_directories(source PUBLIC ${/path_to_directory}/include)替换include_directories(${/path_to_directory}/include).txt。它会影响子目录的 CMakeList .txt 中的源目标。


补充意见和建议

  1. 你想要编译 c++ 源文件,但你定义了CMAKE_C_FLAGS而不是CMAKE_CXX_FLAGS。

  2. 如果您之前设置了CMAKE_C_FLAGS,set (CMAKE_C_FLAGS "-Wall -g")很危险。更喜欢set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -g")

  3. 不建议file(GLOB ...)查找源文件。请参阅文档:

我们不建议使用 GLOB 从源树中收集源文件列表。如果没有 CMakeLists.txt则在添加或删除源时文件会更改,则生成的生成系统无法知道何时要求 CMake 重新生成。

  1. 如果你的主要CMakeLists.txt像你显示的那样简单,add_subdirectory是无用的。您只能在一个主CMakeList中执行所有操作.txt