How do I mangle C++ names (for GCC-compiled objects on Linux)?

361 Views Asked by At

I want to programmatically mangle the name of a C++ function or variable - to get the symbol name which would appear in a compiled object file. I'm using Linux and GCC.

Now, why is this not trivial? e.g. typeid(foo).name()? Because that doesn't do what you want: Consider the following program:

#include <iostream>

extern int foo(int x) { return 0; }
extern double bar(int x) { return 1.0; }

int main()
{
    std::cout << typeid(foo).name() << std::endl;
    std::cout << typeid(bar).name() << std::endl;
}

Let's see what that gives us:

$ g++ -o a.o -O0 -c a.cpp
$ objdump  -t a.o | egrep "(bar|foo)"
00000000000000dd l     F .text  0000000000000015 _GLOBAL__sub_I__Z3fooi
0000000000000000 g     F .text  000000000000000e _Z3fooi
000000000000000e g     F .text  000000000000001b _Z3bari
$ ./a
FiiE
FiiE

Not at all the same thing.

Notes:

  • Were you thinking of namespace abi? So was I. The source doesn't seem to do mangling, only demangling.
  • Solutions for the same problem on other platform+compiler combinations are also interesting, and if you have them I'll expand the question scope.
  • Motivation: I want to dlsym() a non-extern-C function or a variable.
0

There are 0 best solutions below