【问题标题】:Multiple definitions with SimpleJSON library (C++)使用 SimpleJSON 库 (C++) 的多个定义
【发布时间】:2018-04-18 11:24:51
【问题描述】:

我正在使用 SimpleJSON 作为我选择的 JSON 库在 C++ 中编写程序,但遇到了一个奇怪的错误,其中以下(非常简单的)文件在链接时会生成大量错误消息:

jsonobject.hpp:

#ifndef _JSONOBJECT
#define _JSONOBJECT

#include "../../lib/simplejson/json.hpp"

int foo();

#endif

jsonobject.cpp:

#include "jsonobject.hpp"

int foo()
{
   return 0;
}

main.cpp:

#include "jsonobject.hpp"

int main()
{
    return foo();
}

错误信息(我使用g++ *.cpp -std=c++11进行编译):

/tmp/ccMoY6Vl.o: In function `json::Array()':
main.cpp:(.text+0x1cd): multiple definition of `json::Array()'
/tmp/ccjd4YF7.o:jsonobject.cpp:(.text+0x1cd): first defined here
/tmp/ccMoY6Vl.o: In function `json::Object()':
main.cpp:(.text+0x23e): multiple definition of `json::Object()'
/tmp/ccjd4YF7.o:jsonobject.cpp:(.text+0x23e): first defined here
/tmp/ccMoY6Vl.o: In function `json::operator<<(std::ostream&, json::JSON const&)':
main.cpp:(.text+0x2af): multiple definition of `json::operator<<(std::ostream&, json::JSON const&)'
/tmp/ccjd4YF7.o:jsonobject.cpp:(.text+0x2af): first defined here
/tmp/ccMoY6Vl.o: In function `json::JSON::Load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
main.cpp:(.text+0x1a0c): multiple definition of `json::JSON::Load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/tmp/ccjd4YF7.o:jsonobject.cpp:(.text+0x1a0c): first defined here
collect2: error: ld returned 1 exit status

我在这里做错了什么,还是 SimpleJSON 库 (Here it is on GitHub) 的错?

【问题讨论】:

    标签: c++ linker simplejson multiple-definition-error


    【解决方案1】:

    是的,您使用的 SimpleJSON 库有问题。快速查看 json.hpp 可以确认它在头文件中定义了几个命名空间范围的非模板函数,而没有标记它们 inline。这使得无法包含来自多个翻译单元的标题,这严重降低了它的使用方式。

    这已被报告on SimpleJSON's git issue tracker。看起来至少有一个人尝试并提交了对个人分支的修复,但它还没有被拉到主分支。您也许可以从该分支获取代码进行尝试。

    【讨论】:

    • 我今天晚些时候试试,谢谢你的提示。
    • 更新:2021 年问题仍然存在。所以我宁愿寻找替代品。在当前状态下,它无法使用。
    【解决方案2】:

    作者存储库已存档。它现在是只读的。 所以我无法在原始问题板上创建拉取请求或评论。

    我找到了一个拆分为两个文件的解决方案,如下所示: https://github.com/andakkino/SimpleJSON

    我已经用这个内容创建了一个 json.cpp 文件

    #include <json.hpp>
    
    using namespace  json;
    
    JSON JSON::Load( const string &str ) {
        size_t offset = 0;
        return std::move( parse_next( str, offset ) );
    }
    

    在 .hpp 文件中,我在某些函数中添加了“内联”,并且显然消除了加载函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      相关资源
      最近更新 更多