当前位置: 首页> 文旅> 文化 > C++编译时引入json/nlohmann文件报错

C++编译时引入json/nlohmann文件报错

时间:2025/7/12 10:21:22来源:https://blog.csdn.net/Ricardo_XIAOHAO/article/details/140048405 浏览次数:0次

报错信息:

In file included from /home/chenlang/catkin_ws/src/leanrning_communication/src/mysql/../utils/data.h:14:0,from /home/chenlang/catkin_ws/src/leanrning_communication/src/mysql/MyRobotDb.h:32,from /home/chenlang/catkin_ws/src/leanrning_communication/src/mysql/MyRobotDb.cpp:1:
/usr/include/json.hpp: In function ‘bool nlohmann::operator<(nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer>::const_reference, nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer>::const_reference)’:
/usr/include/json.hpp:6057:62: error: wrong number of template arguments (1, should be 2)return *lhs.m_value.array < *rhs.m_value.array;^~~~~
In file included from /usr/include/c++/7/tuple:39:0,from /usr/include/c++/7/mutex:38,from /home/chenlang/catkin_ws/src/leanrning_communication/src/mysql/MyRobotDb.h:10,from /home/chenlang/catkin_ws/src/leanrning_communication/src/mysql/MyRobotDb.cpp:1:
/usr/include/c++/7/array:94:12: note: provided for ‘template<class _Tp, long unsigned int _Nm> struct std::array’struct array^~~~~
leanrning_communication/CMakeFiles/httpserver.dir/build.make:140: recipe for target 'leanrning_communication/CMakeFiles/httpserver.dir/src/mysql/MyRobotDb.cpp.o' failed
make[2]: *** [leanrning_communication/CMakeFiles/httpserver.dir/src/mysql/MyRobotDb.cpp.o] Error 1
make[2]: *** 正在等待未完成的任务....
CMakeFiles/Makefile2:1281: recipe for target 'leanrning_communication/CMakeFiles/httpserver.dir/all' failed
make[1]: *** [leanrning_communication/CMakeFiles/httpserver.dir/all] Error 2
Makefile:140: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make -j20 -l20" failed

错误代码信息:

修改后代码信息:

问题分析 :

  1. 预处理阶段(Preprocessing)

    • 在预处理阶段,编译器会处理 #include 指令,将相应的头文件内容插入到源文件中。在第一段代码中,<iostream><json.hpp> 分别作为独立的指令处理,导致预处理后的源文件中包含了 <iostream><json.hpp> 的内容。
    • 在第二段代码中,<iostream>using namespace std; 被作为一组处理,而 <json.hpp>using namespace nlohmann; 又被作为另一组处理。这种组合不是标准的语法,导致编译器可能无法正确处理这种指令的顺序和作用域,因此可能会出现错误。
  2. 命名空间引入的影响

    • C++中,using namespace 语句应该在全局或函数作用域内使用,而不应该在 #include 指令之间插入。这是因为 using namespace 实际上是一个声明,编译器需要根据它来确定后续代码中名称的解析方式。在第二段代码中,using namespace std;using namespace nlohmann;#include 指令之间被插入,这不符合语法规范,可能导致编译器无法正确解析后续代码。
  3. 编译器错误

    • 当编译器无法正确处理 using namespace 的位置或者指令顺序时,会导致编译错误。例如,可能会出现无法识别的命名空间或者重复定义的错误,这取决于具体的编译器和头文件内容。

总结

  • 错误原因在于#include预处理指令还没有处理完,就插入了命名空间的内容,打乱了指令顺序和作用域,可能json的某些模板指向了std的命名空间.

关键字:C++编译时引入json/nlohmann文件报错

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: