Mac Arm64下CMake编译提示nlohmann/json.hpp未找到的问题
问题描述
项目结构如下:
lib CMakeLists.txt Game include game.h src game.cpp CMakeLists.txt Interpreter include InterpretJson.h src InterpretJson.cpp CMakeLists.txt tools main.cpp CMakeLists.txt CMakeLists.txt
CMake配置情况:
- 在
lib/Interpreter/CMakeLists.txt中配置nlohmann_json依赖:
find_package(nlohmann_json 3.2.0 REQUIRED) add_library(interpreter src/InterpretJson.cpp ) target_link_libraries(interpreter PRIVATE nlohmann_json::nlohmann_json )
InterpretJson.h和game.h均包含#include <nlohmann/json.hpp>lib/Game/CMakeLists.txt中将interpreter库链接到game库:
add_library(game src/game.cpp) target_link_libraries(game PRIVATE interpreter )
CMake执行正常,但执行make时出现差异:
- Linux虚拟机编译正常
- M1 Arm64 Mac下报错:
In file included from /path/to/lib/game/src/game.cpp:1: /path/to/lib/game/include/game.h:9:10: fatal error: 'nlohmann/json.hpp' file not found #include <nlohmann/json.hpp> ^~~~~~~~~~~~~~~~~~~
重复在lib/Game/CMakeLists.txt中配置find_package(nlohmann...)和链接nlohmann_json可解决问题,但存在冗余。希望仅在interpreter中配置一次,让所有依赖它的模块都能使用该头文件。修改VSCode的c_cpp_properties.json添加头文件路径无效:
"includePath": [ "${workspaceFolder}/**", "/opt/homebrew/Cellar/nlohmann-json/3.10.5/include/" ]
问题原因
- 路径搜索差异:Linux下nlohmann_json的头文件可能被安装到系统默认include路径(如
/usr/include),编译器无需CMake显式传递路径即可找到;而M1 Mac上brew安装的nlohmann_json位于/opt/homebrew下,该路径不在编译器默认搜索范围内,必须通过CMake传递include路径。 - CMake依赖传递规则:原配置中interpreter使用
PRIVATE链接nlohmann_json,意味着该依赖仅对interpreter自身编译生效,不会传递给依赖它的game库。因此game编译时无法获取nlohmann_json的include路径,导致头文件找不到。 - VSCode配置不影响编译:
c_cpp_properties.json仅用于编辑器的代码语法提示,不参与实际编译过程,所以修改它无法解决编译时的头文件查找问题。
解决方法
修改lib/Interpreter/CMakeLists.txt中的target_link_libraries,将PRIVATE改为PUBLIC,让nlohmann_json的依赖能传递给所有依赖interpreter的目标:
find_package(nlohmann_json 3.2.0 REQUIRED) add_library(interpreter src/InterpretJson.cpp ) target_link_libraries(interpreter PUBLIC nlohmann_json::nlohmann_json )
这样配置后,game库在链接interpreter时会自动继承nlohmann_json的include路径,无需重复配置,在M1 Mac和Linux上均可正常编译。
内容的提问来源于stack exchange,提问作者callum arul
相关产品推荐
相关产品推荐

