c++linkersimplejsonmultiple-definition-error

Multiple definitions with SimpleJSON library (C++)


I am writing a program in C++ using SimpleJSON as the JSON library of my choice, and have ran into a weird bug, where the following (quite simple) files generate tons of error messages while being linked:

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();
}

The error messages (I am using g++ *.cpp -std=c++11 for compiling):

/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

Am I doing something wrong here, or is this the fault of the SimpleJSON library (Here it is on GitHub)?


Solution

  • Yes, there is a problem with the SimpleJSON library you are using. A quick look at json.hpp confirms it defines several namespace-scope non-template functions in the header file without marking them inline. This makes it impossible to include the header from multiple translation units, which seriously reduces how it can be used.

    This has already been reported on SimpleJSON's git issue tracker. It looks like at least one person has attempted and committed a fix on a personal branch, but it has not yet been pulled to the main branch. You might be able to get code from that branch to try it out.