我是CMake的新手,遇到了以下问题(简化为MWE):
给定的是项目结构
nlohmann_json/
CMakeLists.txt
Example.hpp
Example.cpp
main.cpp文件夹nlohmann_json只是this 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>这里我漏掉了什么?任何帮助都是非常感谢的!
发布于 2021-03-07 22:05:53
你必须添加'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)在导出目标的符号或标头时,还要考虑将链接目标设置为公共的。在您的示例中,您在Example.hpp中包含了nlohmann/json.hpp。因此,在这个头文件上构建的每个人都需要知道nlohmann/json.hpp存储在哪里。
https://stackoverflow.com/questions/66515962
复制相似问题