Is there any way to get back the mangled name from demangled name in g++.
For example , I have the demangled name func(char*, int)
, what should I do to get the mangled name i.e _Z4funcPci
back?
My question is g++ specific.
Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes.
2 Answers. Show activity on this post. Since C is a programming language that does not support name function overloading, it does no name mangling.
Well what you can do is compile your C++ program using g++ and get the .o file. Run the 'nm' command on the .o file thus obtained to get the mangled names! This method is viable on Linux systems.
The need for name mangling arises where the language allows different entities to be named with the same identifier as long as they occupy a different namespace (typically defined by a module, class, or explicit namespace directive) or have different signatures (such as in function overloading).
You can simply use g++ to compile an empty function with the signature you require and extract the name from that. For example:
echo "int f1(char *, int) {} " | g++ -x c++ -S - -o- | grep "^_.*:$" | sed -e 's/:$//'
gives output
_Z2f1Pci
which is I think what you require. Make sure that you include any relevant header files as they will affect the way the symbols are mangled.
Based on the Bojan Nikolic's approach, here's a better script:
mangle.bash:
IFS='::' read -a array <<< "$1" indexes=("${!array[@]}") prefix="" middle="" suffix="" rettype="" if [ -z "$2" ]; then rettype="void" fi for index in "${indexes[@]}" do #echo "$index ${array[index]}" if [ $index == ${indexes[-1]} ]; then #echo "last" middle="$rettype ${array[index]};" elif [ -n "${array[index]}" ]; then #echo "not empty" prefix="${prefix}struct ${array[index]}{" suffix="${suffix}};" fi done #echo "$prefix$middle$suffix $rettype $1{}" echo "$prefix$middle$suffix $rettype $1{}" | g++ -x c++ -S - -o- | grep "^_.*:$" | sed -e 's/:$//'
Use:
$ ./mangle.bash "abc::def::ghi()" _ZN3abc3def3ghiEv $ ./mangle.bash "abc::def::ghi(int i, char c)" _ZN3abc3def3ghiEic $ ./mangle.bash "abc::def::def(int i, char c)" constr _ZN3abc3defC2Eic $ ./mangle.bash "abc::def::~def()" destr _ZN3abc3defD2Ev
But as to constructors and destructors, remember that there are C0 C1 C2 and D0 D1 D2 ones.
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