【问题标题】:cmake mutliple targets - one header only target and another an executablecmake 多个目标 - 一个仅标头目标和另一个可执行文件
【发布时间】:2019-09-05 13:45:55
【问题描述】:

基于这个 stackoverflow 对类似问题 (Cmake include header only target from header only target) 的回答,我正在创建一个仅标头库并尝试在可执行文件中使用它。

我的文件夹结构如下:

├── CMakeLists.txt   // root folder CMake file
├── srcs             // this is the hdr only library
│   ├── src1.hpp
│   ├── CMakeLists.txt
│   ├── src2.hpp
│   └── src3.hpp
│   └── ...
└── test             // this is the executable project
    ├── CMakeLists.txt
    └── main.cpp

根级 CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
project (MyProj CXX) 

add_subdirectory(srcs)
add_subdirectory(test)

src 级 CMakeLists.txt(仅用于标头库)

add_library(MyLib INTERFACE)
target_sources(MyLib  INTERFACE
  "${CMAKE_CURRENT_SOURCE_DIR}/src1.hpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/src2.hpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/src3.hpp"
  )
target_include_directories(MyLib 
  INTERFACE ${CMAKE_CURRENT_BINARY_DIR})
add_subdirectory(plugins)

可执行测试项目的 CMake 文件

add_executable(MyTest main.cpp)

target_sources(MyTest 
    PRIVATE main.cpp
)

target_include_directories(MyTest PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>)

target_link_libraries(MyTest PUBLIC MyLib)

虽然这配置了 cmake 没有警告/错误,但运行 make 失败,表明可执行项目无法从库中找到头文件。

/.../nettu2/test/main.cpp:6:10: 致命错误: src1.hpp: No such 文件或目录#include "src1.hpp" ^~~~~~~~~~~~~~~~ 编译终止。 test/CMakeFiles/MyTest.dir/build.make:62:目标配方 'test/CMakeFiles/MyTest.dir/main.cpp.o' 失败 make[2]: * [test/CMakeFiles/MyTest.dir/main.cpp.o] 错误 1 CMakeFiles/Makefile2:126:目标配方 'test/CMakeFiles/MyTest.dir/all' 失败 make[1]: * [test/CMakeFiles/MyTest.dir/all] 错误 2 Makefile:129: 配方 目标 'all' 失败 make: *** [all] 错误 2

我确信我在这里遗漏了一些关键但微不足道的事情,但仍然无法弄清楚这里出了什么问题。我怎样才能让这个构建工作?

【问题讨论】:

    标签: c++ cmake


    【解决方案1】:

    你在这行有一个小错误:

    target_include_directories(MyLib 
      INTERFACE ${CMAKE_CURRENT_BINARY_DIR})
    

    您为MyLib 指定的包含目录扩展为与srcs 对应的build 目录,即它会导致类似的调用

    clang++ /path/to/build/test/test.cpp -I /path/to/build/srcs ...
    

    但您想将实际的 source 目录传递给预处理器。要解决此问题,请尝试

    target_include_directories(MyLib 
       INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多