c++ - CMake target_include_directories不会影响头文件

标签 c++ cmake

我的项目大致如下所示:

├CMakeLists.txt
|
├───ExampleApp
|   ├───CMakeLists.txt
|   ├───header.hpp
|   └───main.cpp
|
└───ExampleLibrary
    ├───CMakeLists.txt
    ├───mylib.hpp
    └───mylib.cpp

我在根CMakeLists.txt中调用
add_subdirectory(ExampleLibrary)
add_subdirectory(ExampleApp)

要建立该库,我称之为:
add_library(ExampleLibrary
    mylib.hpp mylib.cpp
)

最后,在可执行文件中,我尝试执行以下操作:
add_executable(ExampleApp
    header.hpp main.cpp
)

target_include_directories(ExampleApp
    PRIVATE ${PROJECT_SOURCE_DIR}/ExampleLibrary
)

target_link_libraries(ExampleApp
    Path/To/The/Binary/Directory
)

现在,生成文件可以正常生成,并且项目也可以正确生成。但是,当我现在尝试将mylib.hpp包括在header.hpp中时,由于无法找到文件mylib.hpp,我遇到了构建错误。但是我实际上可以在mylib.hpp中包含main.cpp,并且该项目可以构建和编译。

我想念什么吗?我以为target_include_directories()可同时用于.cpp.hpp文件。

最佳答案

看来您可能没有添加正确的目录作为ExampleApp的包含目录。 PROJECT_SOURCE_DIR变量求值到CMake项目中上次project()调用的目录。您尚未显示此位置,但可以使用CMake项目的目录来确保它是正确的。尝试在${CMAKE_SOURCE_DIR}/ExampleLibrary调用中使用target_include_directories代替:

target_include_directories(ExampleApp
    PRIVATE ${CMAKE_SOURCE_DIR}/ExampleLibrary
)

还有一些注意事项:
  • 如果您不使用Visual Studio之类的IDE进行编译,则无需向add_library()add_executable()之类的调用中添加头文件。这样做只能确保它们显示在IDE中。
  • 而是使用target_include_directories()指定可以在其中找到 header 的目录。就您而言,听起来您应该在此处列出两个目录。
  • 要将ExampleLibrary目标链接到可执行文件,您只需在target_link_libraries()中使用目标名称即可。无需列出二进制目录(除非您从那里链接其他库)。

  • 因此,考虑到这一点,ExampleApp CMake文件可能看起来像这样:
    add_executable(ExampleApp
        main.cpp
    )
    
    target_include_directories(ExampleApp PRIVATE 
        ${PROJECT_SOURCE_DIR}/ExampleLibrary
        ${CMAKE_CURRENT_LIST_DIR}
    )
    
    target_link_libraries(ExampleApp PRIVATE
        ExampleLibrary
    )
    

    关于c++ - CMake target_include_directories不会影响头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61828152/

    相关文章:

    file - "otool"和 "file"可以是 't show architecture of the ".a"文件

    c++ - 赋值运算符,相同的语句

    c++ - 将 C++ 项目移植到 Android

    c++ - 在程序启动时自动执行代码而不违反 ODR

    c++ - 为什么二进制文件不放在 CMAKE_CURRENT_BINARY_DIR 中?

    c++ - VSCode 中的 Google 测试设置帮助

    boost - cmake测试: Every test is run on each ctest

    cmake 未定义的函数引用

    c++ - 在结构 C++ 之间传递数组

    c++ - 为什么 boost::scoped_ptr 会阻止 BCB6 的 PIMPL 惯用法?