首页 > 解决方案 > 链接不适用于`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>

我在这里想念什么?非常感谢任何帮助!

标签: cmake

解决方案


您必须添加“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 存储在哪里。


推荐阅读