How to properly add include directories with CMake(如何使用 CMake 正确添加包含目录)
问题描述
大约一年前,我询问了 CMake 中的标头依赖项.
About a year ago I asked about header dependencies in CMake.
我最近意识到问题似乎是 CMake 认为这些头文件是项目的外部.至少,在生成 Code::Blocks 项目时,头文件不会出现在项目中(源文件会出现).因此,在我看来,CMake 认为这些标头是项目的外部,并且不会在依赖项中跟踪它们.
I realized recently that the issue seemed to be that CMake considered those header files to be external to the project. At least, when generating a Code::Blocks project the header files do not appear within the project (the source files do). It therefore seems to me that CMake consider those headers to be external to the project, and does not track them in the depends.
在 CMake 教程中的快速搜索仅指向 include_directories
这似乎没有做我希望的......
A quick search in the CMake tutorial only pointed to include_directories
which does not seem to do what I wish...
向 CMake 表明特定目录包含要包含的头文件,并且这些头文件应由生成的 Makefile 跟踪的正确方法是什么?
What is the proper way to signal to CMake that a particular directory contains headers to be included, and that those headers should be tracked by the generated Makefile?
推荐答案
必须做两件事.
首先添加要包含的目录:
First add the directory to be included:
target_include_directories(test PRIVATE ${YOUR_DIRECTORY})
如果您坚持使用不支持 target_include_directories
的非常旧的 CMake 版本(2.8.10 或更早版本),您也可以改用旧的 include_directories
:
In case you are stuck with a very old CMake version (2.8.10 or older) without support for target_include_directories
, you can also use the legacy include_directories
instead:
include_directories(${YOUR_DIRECTORY})
然后您还必须将头文件添加到当前目标的源文件列表中,例如:
Then you also must add the header files to the list of your source files for the current target, for instance:
set(SOURCES file.cpp file2.cpp ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_executable(test ${SOURCES})
这样,头文件将作为依赖项出现在 Makefile 中,例如在生成的 Visual Studio 项目中(如果生成的话).
This way, the header files will appear as dependencies in the Makefile, and also for example in the generated Visual Studio project, if you generate one.
如何将这些头文件用于多个目标:
How to use those header files for several targets:
set(HEADER_FILES ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_library(mylib libsrc.cpp ${HEADER_FILES})
target_include_directories(mylib PRIVATE ${YOUR_DIRECTORY})
add_executable(myexec execfile.cpp ${HEADER_FILES})
target_include_directories(myexec PRIVATE ${YOUR_DIRECTORY})
这篇关于如何使用 CMake 正确添加包含目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 CMake 正确添加包含目录


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01