Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange symbol name in output of nm command

Tags:

c

linux

linker

nm

I built a dynamic lib called InterfaceLayer.so. When I call:

> nm InterfaceLayer

As output, I get some symbols that look like:

00000e28  T _Z5startv

while I was expecting it to be "start", just as the name of the function I defined in the code.

Why does this happen?

like image 313
Lelo Avatar asked May 17 '11 19:05

Lelo


3 Answers

That's because of C++ name mangling

nm -C

demangles them.

To prevent name mangling,

  • use a C compiler (gcc, not g++), name your source file .c (not .cpp)
  • or declare extern "C":

.

my.h

  extern "C" 
  {
        void start();
        void finish();
  }

This will give them "C" linkage, meaning they can't be overloaded, cannot pass by reference, nothing c++ :)

like image 148
sehe Avatar answered Oct 14 '22 05:10

sehe


Sounds like C++ name mangling.

like image 39
Ignacio Vazquez-Abrams Avatar answered Oct 14 '22 04:10

Ignacio Vazquez-Abrams


As other answers have mentioned, this is likely becuase of C++ name mangling. If you want the symbol to be accessible by it's 'unmangled' name, and it's implemented in C++, you'll need to us extern "C" to tell the C++ compiler that it has a C linkage.

In the header that has the function prototype, you'll want something like:

#if defined(__cplusplus)
extern "C" {
#endif

// the prototype for start()...


#if defined(__cplusplus)
}
#endif

This will ensure that if the function is used by a C++ compiler, it'll get the extern "C" on the declaration, and that if it's used by a C module, it won't be confused by the extern "C" specifier.

You implementation in the .cpp file doesn't need that stuff if you include the header before the function definition. It'll use the linkage specification it saw from the previous declaration. However, I prefer to still decorate the function definition with extern "C" just to ensure that everything is in sync (note that in the .cpp file you don't need the #ifdef preprocessing stuff - it'll always be compiled as C++.

like image 45
Michael Burr Avatar answered Oct 14 '22 04:10

Michael Burr