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

时间秒杀一切 提交于 2021-01-29 08:53:01

问题


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.


回答1:


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++ 



回答2:


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.



来源:https://stackoverflow.com/questions/65739215/undefined-reference-to-stdostreamoperatorunsigned-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!