Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

undefined reference to > `std::ostream::operator<<(unsigned long)'

I have the following code:

#include <sstream>
using namespace std;

int
main ()
{
        ostringstream oss;
        unsigned long k = 5;
        oss << k;
}

Compiled with the following parameters:

/usr/local/gcc-10.2.0/bin/g++ -I/usr/local/gcc-10.2.0/include -L/usr/local/gcc-10.2.0/lib64 -Wl,-rpath,/usr/local/gcc-10.2.0/lib64 -lstdc++ b.cpp

Got the following output:

/tmp/cclRSXGV.o: In function main': b.cpp:(.text+0x35): undefined reference to std::ostream::operator<<(unsigned long)'

collect2: error: ld returned 1 exit status

What is needed to get it to compile and link correctly?

Using GNU gcc 10.2.0.

Upvotes: -1

Views: 3167

Answers (2)

Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

Turns out, it will compile with:

/usr/local/gcc-10.2.0/bin/g++ -I/usr/local/gcc-10.2.0/include -L/usr/local/gcc-10.2.0/lib64 -Wl,-rpath,/usr/local/gcc-10.2.0/lib64 b.cpp -lstdc++ /usr/local/gcc-10.2.0/lib64/libstdc++.a

I just need to specific the exact libstdc++.a after the cpp file. While I worried that this would cause libstdc++.a to be statically linked, I don't think it will. Static linking requires -static-libstdc++.

Still can't figure out why I need to specify libstdc++.a when my earlier gcc (4.4.7) didn't need it.

Upvotes: 0

wcochran
wcochran

Reputation: 10896

When you specify what libraries to link the order matters. In this order

-lstdc++ b.cpp

libstdc++ will not resolve any symbols in b.cpp. Specify the library afterwords:

b.cpp -lstdc++ 

Upvotes: 1

Related Questions