c++ CMake:有些包含在源文件中定义的目录,但在嵌套目标的标头中未定义

uyto3xhc  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(124)

鉴于以下项目结构:

.
└── library/
    ├── CMakeLists.txt
    ├── include/
    │   └── class1.hpp
    ├── src/
    │   └── class1.cpp
    ├── build/
    │   ├── _deps/
    │   │   └── fmt-build
    │   └── sample/
    │       └── app_using_library.exe
    └── sample/
        ├── CMakeLists.txt
        └── main.cpp

程式库的CMakeLists.txt:

project(library)

include(FetchContent)

FetchContent_Declare(
        fmt
        URL https://github.com/fmtlib/fmt/releases/download/9.1.0/fmt-9.1.0.zip
)
FetchContent_MakeAvailable(fmt)

add_library(library STATIC 
  "src/class1.cpp" 
  "include/class1.hpp" 
target_include_directories(library PUBLIC include)
target_link_libraries(library PRIVATE fmt::fmt)

应用程序使用库的CMakeLists.txt文件:

project(app_using_library)
add_executable(app_using_library main.cpp)
target_link_libraries(app_using_library PRIVATE library)

class1.hpp:
#include "fmt/core.h" // cannot open source file "fmt/core.h"
class1.cpp:
#include "fmt/core.h" // works fine
在构建libraryapp_using_library时,fmt头文件可以包含在class1.cpp中,而不能包含在class1.hpp中,是否有可能的原因或解释?在仅构建library时,include在头文件中工作正常
编译器无法在“class1.hpp”中找到fmt头文件,但可以在“class1.cpp”中找到它们。
全错误:

FAILED: sample/CMakeFiles/app_using_library.dir/main.cpp.obj 
  C:\msys64\mingw64\bin\g++.exe  -ID:/Programming/cpp/library/include -g -std=gnu++20 -MD -MT sample/CMakeFiles/app_using_library.dir/main.cpp.obj -MF sample\CMakeFiles\app_using_library.dir\main.cpp.obj.d -o sample/CMakeFiles/app_using_library.dir/main.cpp.obj -c D:/Programming/cpp/library/sample/main.cpp
  In file included from D:/Programming/cpp/library/sample/main.cpp:2:
  D:/Programming/cpp/library/include/class1.hpp:4:10: fatal error: fmt/core.h: No such file or directory
      4 | #include "fmt/core.h"
        |          ^~~~~~~~~~~~
  compilation terminated.
bvhaajcl

bvhaajcl1#

编译“app_using_library”时失败,因为只有“library”知道fmt。要解决此问题,还需要将已定义的有关fmt的信息包含到app_using_library CMakeLists.txt中

相关问题