Back: Template Instantiation
Forward: How GNU Autotools Can Help
 
FastBack: How GNU Autotools Can Help
Up: Compiler Quirks
FastForward: How GNU Autotools Can Help
Top: Autoconf, Automake, and Libtool
Contents: Table of Contents
Index: Index
About: About this document

16.3.2 Name Mangling

Early C++ compilers mangled the names of C++ symbols so that existing linkers could be used without modification. The cfront C++ translator also mangled names so that information from the original C++ program would not be lost in the translation to C. Today, name mangling remains important for enabling overloaded function names and link-time type checking. Here is an example C++ source file which illustrates name mangling in action:

 
class Foo
{
public:
  Foo ();

  void go ();
  void go (int where);

private:
  int pos;
};

Foo::Foo ()
{
  pos = 0;
}

void
Foo::go ()
{
  go (0);
}

void
Foo::go (int where)
{
  pos = where;
}

int
main ()
{
  Foo f;
  f.go (10);
}

$ g++ -Wall example.cxx -o example.o

$ nm --defined-only example.o
00000000 T __3Foo
00000000 ? __FRAME_BEGIN__
00000000 t gcc2_compiled.
0000000c T go__3Foo
0000002c T go__3Fooi
00000038 T main

Even though Foo contains two methods with the same name, their argument lists (one taking an int, one taking no arguments) help to differentiate them once their names are mangled. The `go__3Fooi' is the version which takes an int argument. The `__3Foo' symbol is the constructor for Foo. The GNU binutils package includes a utility called c++filt that can demangle names. Other proprietary tools sometimes include a similar utility, although with a bit of imagination, you can often demangle names in your head.

 
$ nm --defined-only example.o | c++filt
00000000 T Foo::Foo(void)
00000000 ? __FRAME_BEGIN__
00000000 t gcc2_compiled.
0000000c T Foo::go(void)
0000002c T Foo::go(int)
00000038 T main

Name mangling algorithms differ between C++ implementations so that object files assembled by one tool chain may not be linked by another if there are legitimate reasons to prohibit linking. This is a deliberate move, as other aspects of the object file may make them incompatible--such as the calling convention used for making function calls.

This implies that C++ libraries and packages cannot be practically distributed in binary form. Of course, you were intending to distribute the source code to your package anyway, weren't you?


This document was generated by Gary V. Vaughan on February, 8 2006 using texi2html