I find very frustrating to have to fix C++ errors happening at linkage time (especially undefined reference errors) due to the fact that all the function names are mangled. An example of mangled name:
_ZNK5boost7archive6detail11oserializerINS0_13text_oarchiveEN9galandria8UniverseEE16save_object_dataERNS1_14basic_oarchiveEPKv
It is so hard to read, and finding the actual function is even harder.
Is there a way to convince ld
to output demangled names?
ld
(The GNU Linker) is able to demangle C++ function names. ld
documentation on demangling from it's man
page: (available here online)
--demangle[=style]
--no-demangle
These options control whether to demangle symbol names in error
messages and other output. When the linker is told to demangle,
it tries to present symbol names in a readable fashion: it strips
leading underscores if they are used by the object file format,
and converts C++ mangled symbol names into user readable names.
Different compilers have different mangling styles. The optional
demangling style argument can be used to choose an appropriate
demangling style for your compiler. The linker will demangle by
default unless the environment variable COLLECT_NO_DEMANGLE is
set. These options may be used to override the default.
Let's see an example:
void foo();
void foo(int);
int main() {
foo();
foo(5);
}
This is a simple valid code. This will compile but fail to link successfully because there is no implementation of foo()
and foo(int)
here. Now we'll compile it with the following command:
g++ main.cpp -c -o main.o
It will compile successfully. Now let's try to link it with demangling disabled with the following command:
g++ main.o -Wl,--no-demangle
It should show linking errors with some weird mangled name like this:
main.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `_Z3foov'
main.cpp:(.text+0xf): undefined reference to `_Z3fooi'
collect2: error: ld returned 1 exit status
See live on Coliru
Now let's try to link with demangling enabled with the following command:
g++ main.o -Wl,--demangle
We'll get errors with demangled function names with their arguments like this:
main.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
main.cpp:(.text+0xf): undefined reference to `foo(int)'
collect2: error: ld returned 1 exit status
See live on Coliru
Here -Wl
means arguments to linker.
As far as I know, g++
enables demangling automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With