如何使用 CMake 正确添加包含目录

时间:2023-03-23
本文介绍了如何使用 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 正确添加包含目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:存储此指针以在 WndProc 中使用的最佳方法 下一篇:如何在 Ubuntu 上安装 OpenSSL 库?

相关文章

最新文章