Demangle an object code symbol generated by G++
Content |
Tested on |
Debian (Etch, Lenny, Squeeze) |
Ubuntu (Lucid, Maverick, Natty, Precise, Trusty) |
Objective
To take a mangled symbol from object code that was generated by G++ and convert it to the corresponding unmangled form.
Background
The C++ programming language allows functions to be overloaded, meaning that they can have the same name provided that they have different signatures. For example, there could be two functions called foo
, one accepting a const char*
and one accepting a const std::string&
:
void foo(const char* s); void foo(const std::string& s);
G++ (like most C++ compilers) implements this behaviour by mangling. This is a process whereby the name and signature of each function are encoded as a string, in a form that is acceptable to the linker as a symbol name. The encoding method has not been standardised so may depend on the compiler.
In most cases the result is not easily human-readable. For example, using G++ 4.3, the mangled forms of the functions declared above are _Z3fooRKSs
and _Z3fooPKc
.
Scenario
Suppose that a program has terminated with a stack backtrace that includes the symbol _Z3fooPKc
. You wish to demangle this symbol in order to make it readable.
Method
Symbols generated by G++ can be demangled using the c++filt
command:
c++filt _Z3fooPKc
The output is similar in form to a function declaration as might appear in the source code, but does not include the return type (because that is not part of the function signature):
foo(char const*)
Variations
Using c++filt as a filter
As its name suggests c++filt
can be used as filter, taking its input from stdin
and sending the demangled output to stdout
. In this mode the symbol names can be embedded in other text, which passes through the filter without being altered. For example, following command lists the symbol table of foo.o
in demangled form:
objdump -t foo.o | c++filt
(In this particular case the same effect can be achieved using the --demangle
option of objdump
.)
If the requirement is to demangle the content of stderr
(because, for example, a program has terminated with a stack backtrace) then this can be done using the 2|
redirection operator:
./a.out 2| c++filt
Further reading
- Margaret A Ellis and Bjarne Stroustrup, The Annotated C++ Reference Manual, ISBN 0-201-51459-1, AT&T, 1990, pp122-127
Tags: c++