問題描述
大約一年前,我詢問了 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模板網!