【问题标题】:CMake does not include path to link libraries when compilingCMake 编译时不包含链接库的路径
【发布时间】:2020-04-01 12:35:46
【问题描述】:

所以我的目录结构是这样的

/
-- CMakeLists.txt

-- bencode/
---- bType.hpp
---- bType.cpp
---- Decoder.hpp
---- Decoder.cpp
---- CMakeLists.txt

-- torrent/
---- main.cpp
---- Torrent.hpp
---- Torrent.cpp
---- Tracker.hpp
---- Tracker.cpp
---- CMakeLists.txt

根 CMakeLists.txt 是

cmake_minimum_required(VERSION 3.16)
project(Torrent VERSION 1.0.0)
add_subdirectory(bencode)
add_subdirectory(torrent)

bencode/CMakeLists.txt是

add_library(
    Decoder
    Decoder.hpp
    Decoder.cpp
)
add_library(
    bType
    bType.hpp
    bType.cpp
)
target_include_directories(bType PRIVATE "${CMAKE_CURRENT_SOURCE/_DIR}")
target_include_directories(Decoder PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")

torrent/CMakeLists.txt 是

add_library(
    Torrent
    Torrent.hpp
    Torrent.cpp
)
add_library(
    Tracker
    Tracker.hpp
    Tracker.cpp
)
add_executable(main main.cpp)
target_link_libraries(
    main PRIVATE
    Torrent Tracker
    Decoder bType
)

每当我构建时,Torrent.cpp 编译失败,因为它包含不在同一目录中的Decoder.hpp,并且构建命令在编译过程中不包含路径

[build] ../torrent/Torrent.cpp:5:10: fatal error: Decoder.hpp: No such file or directory
[build]  #include <Decoder.hpp>
[build]           ^~~~~~~~~~~~~
[build] comp

编译时应该有一个-I 标志,但没有。

帮我找出原因?

【问题讨论】:

    标签: c++ build cmake compiler-errors


    【解决方案1】:

    如果您将Decoder.hpp 的位置设置为Decoder 的public 包含目录,并使用target_link_libraries 将Torrent 链接到Decoder,CMake 会选择您需要Torrent 搜索正确的位置以找到Docoder 的标题。

    【讨论】:

      【解决方案2】:

      您已将所有库目标链接到main,但如果Torrent 库和Decoder 库之间存在依赖关系,则应链接强> Decoder 到 Torrent 也。要将Decoder 库的包含目录传播到Torrent 库,请改用target_include_directories() 调用中的PUBLIC 参数。

      bencode/CMakeLists.txt:

      add_library(
          Decoder
          Decoder.hpp
          Decoder.cpp
      )
      add_library(
          bType
          bType.hpp
          bType.cpp
      )
      target_include_directories(bType PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
      # Use PUBLIC here to propagate the include directories to consumers.
      target_include_directories(Decoder PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
      

      torrent/CMakeLists.txt:

      add_library(
          Torrent
          Torrent.hpp
          Torrent.cpp
      )
      add_library(
          Tracker
          Tracker.hpp
          Tracker.cpp
      )
      add_executable(main main.cpp)
      
      # Link Decoder to Torrent here, because Torrent depends on Decoder.
      target_link_libraries(Torrent PUBLIC Decoder)
      
      # Link the other libraries to main, Decoder will be brought along with Torrent.
      target_link_libraries(
          main PRIVATE
          Torrent 
          Tracker
          bType
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        • 2017-12-17
        相关资源
        最近更新 更多