CMake 项目中带有前缀的头文件 [英] Header files with prefix in CMake project
问题描述
我已经建立了一个 CMake 项目,其目录结构如下所示:
I have set up a CMake project whose directory structure looks as follows:
src/
--CMakeLists.txt
--libA/
----CMakeLists.txt
----foo.h
----foo.cpp
--main/
----CMakeLists.txt
----main.cpp
src/CMakeLists.txt
使用 add_subdirectory
来拉入 libA
和 main
.libA/CMakeLists.txt
使用add_library
定义了一个名为libA
的库,它通过 导出
.如果我现在使用 foo.h
>target_include_directoriestarget_link_library
链接 main
中的 libA
,我可以通过 # 包含
.foo.h
在 main.cpp
中包含
src/CMakeLists.txt
uses add_subdirectory
to pull in libA
and main
. libA/CMakeLists.txt
uses add_library
to define a library called libA
, which exports foo.h
via target_include_directories
. If I now link against libA
in main
using target_link_library
, I can include foo.h
via #include <foo.h>
in main.cpp
.
问题: 是否可以为 libA
的公共接口提供一个前缀,以便我可以(并且必须)编写 #include <在
吗?main.cpp
中代替 libA/foo.h>
Question: Is it possible to provide the public interface of libA
with a prefix, so that I can (and have to) write #include <libA/foo.h>
in main.cpp
instead?
推荐答案
您可以使用 root 源目录(或作为 libA
父目录的其他目录)在 target_include_directories()
调用中.这将允许定义 INTERFACE_INCLUDE_DIRECTORIES
目标属性相对于另一个目录(在本例中,CMAKE_SOURCE_DIR
).所以它看起来像这样:
You can use the root source directory (or some other directory which is a parent to libA
) in the target_include_directories()
call. This will allow the INTERFACE_INCLUDE_DIRECTORIES
target property to be defined with respect to another directory (in this example, the CMAKE_SOURCE_DIR
). So it would look something like this:
在libA/CMakeLists.txt
中:
add_library(libA foo.cpp)
# Define the include files with respect to the directory above this.
target_include_directories(libA PUBLIC ${CMAKE_SOURCE_DIR})
main/main.cpp
文件:
#include <iostream>
#include <libA/foo.h>
int main() {
FooClass fooclass;
fooclass.myFunction();
std::cout << "Hello World!" << std::endl;
return 0;
}
这篇关于CMake 项目中带有前缀的头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!