Archive

Posts Tagged ‘name mangling’

C/C++ 轧名规则(name mangling)简介

August 18th, 2007 yaker 1 comment

[简介]
LINK 2019应该都见得比较多了,随便搜索一个得到一个
error lnk2019: unresolved external symbol
“__declspec(dllimport) public: virtual __thiscall osgviewer::viewer::~viewer(void)”
(__imp_??1viewer@osgviewer@@uae@xz) referenced in function _wmain
注意这个:__imp_??1viewer@osgviewer@@uae@xzf
这就是函数轧名后的结果
轧名解决了现代编程语言中的很多问题,比如重载等等。它为连接器提供了额外的信息,在编译器和连接器之间传递信息。
[C语言中的轧名]
非常遗憾的说,C语言中也有轧名。
wikipedia上的题目是:C name decoration in Microsoft Windows。因为轧名规则最早由微软提出,并且由其他各大编译器厂商普遍采用。注意这里name decoration和name mangling有同样的意思。实际上像C一样不支持重载的语言,并不怎么需要轧名。轧名在C语言中可以为函数提供额外信息,比如调用预定(calling conventions)。例如在Windows平台上支持三种调用约定。
比如以下函数

int __cdecl    f (int x) { return 0; }
int __stdcall  g(int y) { return 0; }
int __fastcall h(int z) { return 0; }
/* 使用32为编译器,轧名后的结果为 */
_f
_g@4
@h@4

P.S. 32位的汇编编译器下也是同样的
[C++轧名规则]
C++的轧名规则比不是那么统一,可以见reference1里的表格,各大编译器产品都有自己的标准
非命名空间里的函数,非成员函数
void h(int)
轧名结果:
GNU GCC 3.x _Z1hi  _Z1hi
Microsoft VC++ v6/v7 ?h@@YAXH@Z
见reference来得到更多信息,讲的Visual Studio下的轧名规则,写的很详尽,这里转帖一些

Preliminary Notes
These are surely inaccurate, but it’s a start. Mangled function names have the following pieces, in order:
1.a prefix of ‘?’
2.the function’s name (ignoring any class). Operators, constructors, and destructors are represented by two-character codes;
3.If the function is not an operator, the separator ‘@’ terminates the function name.
4.If the name is qualified by a class name:
1.For each qualifying class name from inner to outer, the encoded class name followed by the separator ‘@’.
2.the separator ‘@’
3.the value “Q”
else
1.the separator ‘@’
2.the value “Y”
5.the encoded function calling convention
6.the encoded signature of the function’s return value
7.the encoded signature of the function’s arguments
8.a suffix of ‘Z’

[Reference]
1.Name mangling(wikipedia)
2.C++ Name Mangling/Demangling
P.S. wikipedia能访问多方便啊

Categories: C++ Tags: ,