Search code examples
macosmakefilelinkerarmc++17

g++ in mac gives `duplicate symbol error`


I have a .o file, which when I update a few times and compile, I get an error: duplicate symbol '__ZlsRSoRKSt6vectorIiSaIiEE' in: /var/folders/q3/ykn_sbq97hn6cn73_40jlhrc0000gp/T//ccvDBwwZ.o t1.o duplicate symbol '__ZlsRSoRKSt6vectorIbSaIbEE' in: /var/folders/q3/ykn_sbq97hn6cn73_40jlhrc0000gp/T//ccvDBwwZ.o t1.o ld: 2 duplicate symbols for architecture arm64 collect2: error: ld returned 1 exit status make: *** [compiler] Error 1

My MakeFile looks as follows:

INITFILE_Scanner = scanner.l
INITFILE_Grammar = grammar.ypp

compiler: lex.yy.c grammar.tab.cpp main.cpp lib/parse_tree.h t1.o
        @g++ -std=c++11 main.cpp grammar.tab.cpp lex.yy.c t1.o -o prog

transducers.o: t1.h t1.cpp
        @g++ -c t1.cpp -o t1.o
        
lex.yy.c: $(INITFILE_Scanner)
            @lex -w $(INITFILE_Scanner)

grammar.tab.cpp: $(INITFILE_Grammar)
            @bison -d $(INITFILE_Grammar)

Is the above error because of some specific reason? I am not sure whether it is a compilation error or linking error, how do I resolve it?

I tried changing the code a bit, but this doesn't seem to resolve it.


Solution

  • If you have access to the tool c++filt you can see where the mangled name __ZlsRSoRKSt6vectorIiSaIiEE comes from:

    % c++filt -_  __ZlsRSoRKSt6vectorIiSaIiEE
    operator<<(std::basic_ostream<char, std::char_traits<char> >&, 
               std::vector<int, std::allocator<int> > const&)
    

    This means that you've defined the operator<< overload taking a std::ostream& and aconst std::vector<int>& in multiple translation units (probably by defining it in a header file) and therefore have a one definition rule violation.

    You can fix it by making your function inline:

    inline std::ostream& operator<<(std::ostream& os, 
                                    const std::vector<int>& vec) {
        //...
    }
    

    ... or by only declaring it in the header file and defining it in one of your .cpp files.