简体   繁体   English

CMake 强制包含语句以具有 #include 格式<mylib header.h></mylib>

[英]CMake force include statements to have form #include <mylib/header.h>

I'm currently working on a project with different libraries, where some of their files have similar/equal names or similar/equal names as STL files.我目前正在开发一个具有不同库的项目,其中一些文件具有与 STL 文件相似/相同的名称或相似/相同的名称。 This may lead to confusion at a later point in time.这可能会在以后的某个时间点导致混乱。 Therefore, even it's handy to include my custom library headers by just writing #include<file.h> , I'd like to refactor my CMake code in a way that I have to include my headers like this: #include<mylib/file.h> .因此,即使通过编写#include<file.h>来包含我的自定义库头文件很方便,我也想重构我的 CMake 代码,以便我必须像这样包含我的头文件: #include<mylib/file.h>

How can I do so?我该怎么做?

Here is an example of my current setup:这是我当前设置的示例:

CMakeLists.txt
     |
     |- mylib
     |   |- CMakeLists.txt
     |   |- include
     |        |- header1.h
     |        |- header2.h
     |
     |- test
         |- CMakeLists.txt
         |- mylib
              |- header1_test.cpp   
              |- header2_test.cpp  

Where the three CMakeLists.txt are:三个CMakeLists.txt分别是:

# main CMakeLists.txt

# ... requirements, etc. ...

# ... fetch and include GoogleTest ...

add_subdirectory(mylib)
add_subdirectory(test)
# mylib/CMakeLists.txt

add_library(mylib INTERFACE)
target_include_directories(mylib INTERFACE include/)
# test/CMakeLists.txt

# link directories
link_directories(../mylib)

# test executable
add_executable(header1_test mylib/header1_test.cpp)
add_executable(header2_test mylib/header2_test.cpp)

# link libraries
target_link_libraries(header1_test PRIVATE mylib PRIVATE gtest_main)
target_link_libraries(header2_test PRIVATE mylib PRIVATE gtest_main)

# discover tests
gtest_discover_tests(header1_test)
gtest_discover_tests(header2_test)

To complete comment from Tsyvarev, you need to modify your header location:要完成 Tsyvarev 的评论,您需要修改您的 header 位置:

[...]
 |   |- include
 |   |   |- mylib
 |   |   |   |- header1.h
 |   |   |   |- header2.h

On a side note, the line:在旁注中,该行:

# link directories
link_directories(../mylib)

is not needed.不需要。 This function should be used when you need to link with a library that is not part of your CMake project and in a different location that your linker doesn't search by default.当您需要链接不属于您的 CMake 项目的库并且位于您的 linker 默认不搜索的不同位置时,应使用此 function。 Here, you create your lib mylib via add_library and everything is under the same CMake project (you have a root CMakeLists that adds 2 subdirectories).在这里,您通过 add_library 创建 lib mylib ,所有内容都在同一个 CMake 项目下(您有一个添加 2 个子目录的根 CMakeLists)。

Also, you don't need to duplicate the keyword PRIVATE :此外,您不需要复制关键字PRIVATE

target_link_libraries(header2_test PRIVATE mylib gtest_main)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM