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 正确添加包含目录
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01