gcc 11 link error only when optimization disabled

219 views Asked by At

I am facing this weird issue with gcc 11.3.0, a -O3 build works, whereas when I build with -O0 -g (debug build), I get linker error:

/usr/bin/ld: path/to/mylib.a(my_file.cpp.2.o): undefined reference to symbol '_ZNSt6localeD1Ev@@GLIBCXX_3.4'
/usr/bin/ld: /lib/x86_64-linux-gnu/libstdc++.so.6: error adding symbols: DSO missing from command line

From other answers on similar topic, I tried to add -lstdc++ but that gave a lot more errors! Is this a C vs CPP link issue ? If so, why do I see it only with -O0 and not -O3 ?

How to fix this ? (how to check which library the symbol is coming from?)

-- Thanks

2

There are 2 answers

0
Shahid Roofi Khan On

-o0 (setting optimizations level to zero) does not only mean disabling optimizations it also entails that debugging should work. Reference: What's the difference between a compiler's `-O0` option and `-Og` option?

This means the reference symbols should resolve.

In case of optimized build that is automatically getting ignored however with -o0 that is becoming an issue so you need to explicitly ignore them using --unresolved-symbols=ignore-in-object-files switch.

0
Ani On

The library .a (ar archive) had all C objects but just 1 .cpp! So, I tried adding -lstdc++ at link, but that pops up a lot of unresolved symbols.

Note: -lstdc++ is same as linking using g++ (instead of gcc)

The symbol is coming from some external library (most likely boost):

$ c++filt _ZNSt6localeD1Ev
std::locale::~locale()

Adding -Wl,--unresolved-symbols=ignore-in-object-files when the compile is done with -O0 solves the problem (ignore if its coming from regular object files).