cmake - 链接不适用于`add_subdirectory`
问题描述
我是 CMake 新手,遇到以下问题(简化为 MWE):
给定的是项目结构
nlohmann_json/
CMakeLists.txt
Example.hpp
Example.cpp
main.cpp
文件夹 nlohmann_json 只是这个 repo的一个克隆。
这是文件的内容:
// Example.hpp
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
#include <fstream>
#include <nlohmann/json.hpp>
void json_test();
#endif // EXAMPLE_HPP
// Example.cpp
#include "Example.hpp"
using nlohmann::json;
#include <fstream>
void json_test() {
json jsonfile;
jsonfile["foo"] = "bar";
std::ofstream file("key.json");
file << jsonfile;
}
// main.cpp
#include "Example.hpp"
int main() {
json_test();
return 0;
}
cmake_minimum_required(VERSION 3.0.0)
project(MWE VERSION 0.1.0)
# Use C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_subdirectory(nlohmann_json)
add_library(Example STATIC Example.cpp Example.hpp)
add_executable(main main.cpp)
target_link_libraries(main PRIVATE Example)
target_link_libraries(main PRIVATE nlohmann_json)
不幸的是,在构建时,我得到
[build] /Users/klaus/Desktop/cmake_json_mwe2/Example.hpp:5:10: fatal error: 'nlohmann/json.hpp' file not found
[build] #include <nlohmann/json.hpp>
我在这里想念什么?非常感谢任何帮助!
解决方案
您必须添加“nlohmann_json”作为静态库的链接目标:
cmake_minimum_required(VERSION 3.0.0)
project(MWE VERSION 0.1.0)
# Use C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_subdirectory(nlohmann_json)
add_library(Example STATIC Example.cpp Example.hpp)
target_link_libraries(Example PRIVATE nlohmann_json)
add_executable(main main.cpp)
target_link_libraries(main PRIVATE Example)
在导出目标的符号或标头时,还应考虑将链接目标设为 PUBLIC。在您的示例中,您将 nlohmann/json.hpp 包含在 Example.hpp 中。因此,针对此标头构建的每个人还需要知道 nlohmann/json.hpp 存储在哪里。
推荐阅读
- dns - 如何在没有登录的情况下在 MediaWiki 中启用图像和文档上传
- javascript - 将字符串更改为新日期
- git - 如何恢复“无法访问的 blob”,我通过“git glean -df”删除了桌面上的所有目录
- r - 如何遍历确定的行范围?
- linux - shell/bash 编码中的 `&` 和 `#` 是什么意思?请解码 Bash 脚本的行
- angular - Angular:RxJs .switchMap() 调用后端 - 最佳结构?
- excel - 多次保存文件
- node.js - 在 HttpsCallableResult 完成之前等待所有回调返回
- c++ - 如何在 Xcode C++ 中使用 dlib?
- javascript - 如何从不同的网站获取 pdf 文件并将其显示在我们的网站上而不进行重定向?