Posts tagged name mangling

What is Name Mangling and how to disable Name Mangling?

1

What is Name Mangling?
Name mangling is the technique used by C++ to generate unique names. C++ uses name mangling to implement function overloading etc. For instance, if you have two overloaded functions, while compiling the source, compiler will internally rename your function to uniquely generated function name. The function name is generated from the parameter list and a couple of other factors.

Check the links for the name mangling algorithm by Visual C++.
http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling
http://www.kegel.com/mangle.html

Have a look at mangled C++ function names below.

Well, Name Mangling is nice. But it have one problem. You cannot call your exported C++ function from C code. Because, C++ compiler mangles the function name and renames the fuction and exposes the mangled function name. So in order for C source to call C++ function, you’ve to disable name mangling for those functions. But how?


You can disable name mangling by declaring the function as extern “C”. Have a look at the code snippet.

// Disable name Mangling for single function.
extern "C" void Function( int a, int b );

// Disable name Mangling for group of functions.
extern "C"
{
    void Function1( char a, char  b );
    void Function2( int a, int   b );
    void Function3( float a, float b );
}


If you want to get the function name from a mangled name, then have a look at my previous post -
http://weseetips.com/2008/04/14/name-mangling-how-to-undecorate-a-c-decorated-function-name/


Targeted Audience – Beginners.

Name Mangling – How to Undecorate a decorated C++ function name.

11


For generating unique function names C++ decorates the function names to wired form. This is best known as Name Mangling. You can see sample of decorated function names by using dependency walker. Open any DLL in dependency walker and in the exported section, most probably you can see a list of decorated function names.


So, if you want to see the real function prototype of that decorated function name, what to do? Just use, UnDecorateSymbolName() function. Please see the following code block.

// Buffer for undecorating Function Name.
TCHAR tchUnDecoratedName[ 512 ];

// The Decorated function Name.
TCHAR tchDecoratedName[] =
_T( "?classCDataPathProperty@CDataPathProperty@@2UCRuntimeClass@@B" );

if( UnDecorateSymbolName( tchDecoratedName,     // Decorated Name.
                          tchUnDecoratedName,   // UnDecorated Name.
                          512,                  // Buffer size.
                          UNDNAME_COMPLETE ))   // Flags.
{
    // Display the undecorated function name.
    CString csUndecoratedName( tchUnDecoratedName );
    AfxMessageBox( csUndecoratedName );
}


Don’t forget to include the header file – “Dbghelp.h” and library file – “Dbghelp.lib“.


Targeted Audience – Intermediate.

Go to Top