问题描述
我想学习和了解的名字用C ++重整。这里有一些问题:
I am trying to learn and understand name mangling in C++. Here are some questions:
(1)从
当一个全局函数被重载,每个重载版本生成的重整名称是独一无二的。名称重整也适用于变量。因此,一个局部变量并使用相同的用户名给出一个全局变量仍然得到明显的错位的名称。
是正在使用名字改编,除了重载函数和相同名称的全局和局部变量还有其他的例子吗?
Are there other examples that are using name mangling, besides overloading functions and same-name global and local variables ?
(2)从
的需要时,其中该语言允许不同实体具有相同标识符,只要它们占据不同的空间(其中一个命名空间通常是由一个模块,类或明确的namespace指令定义)进行命名。
我不明白为什么名字改编仅适用于该情况下,当识别属于不同的命名空间,因为重载函数可以在同一个命名空间和相同名称的全局和局部变量,也可以在同一空间。如何理解?
I don't quite understand why name mangling is only applied to the cases when the identifiers belong to different namespaces, since overloading functions can be in the same namespace and same-name global and local variables can also be in the same space. How to understand this?
执行具有相同名称的变量,但在不同的范围也使用名称重整?
Do variables with same name but in different scopes also use name mangling?
(3)是否c具有名字改编?如果没有,怎么能处理的情况下,当一些全局和局部变量具有相同的名称? C没有重载函数,对吧?
(3) Does C have name mangling? If it does not, how can it deal with the case when some global and local variables have the same name? C does not have overloading functions, right?
感谢和问候!
推荐答案
C没有做名字改编,但它确实pre-挂起下划线的功能名称,因此的printf(3 )
实际上 _printf
是在libc中的对象。
C does not do name mangling, though it does pre-pend an underscore to function names, so the printf(3)
is actually _printf
in the libc object.
在C ++中的故事是不同的。它的历史是最初创建SroustrupC与类或,编译器将转换早期C ++到C然后的其他工具 - C编译器和连接器将我们用于生产目标code。这意味着,C ++名称必须以某种方式转换为C名称。这正是一样。它为每个类成员和全局/命名空间功能和变量都有一个独特的名字,所以命名空间和类名(分辨率)和参数类型(重载)在某种程度上包含在最终的链接名称。
In C++ the story is different. The history of it is that originally Sroustrup created "C with classes" or cfront, a compiler that would translate early C++ to C. Then rest of the tools - C compiler and linker would we used to produce object code. This implied that C++ names had to be translated to C names somehow. This is exactly what name mangling does. It provides a unique name for each class member and global/namespace function and variable, so namespace and class names (for resolution) and argument types (for overloading) are somehow included in the final linker names.
这是很容易看到像 - 编译C ++源代码,并期待在生成的符号。下面是关于OSX与海湾合作委员会:
This is very easy to see with tools like nm(1)
- compile your C++ source and look at the generated symbols. The following is on OSX with GCC:
namespace zoom
{
void boom( const std::string& s )
{
throw std::runtime_error( s );
}
}
~$ nm a.out | grep boom
0000000100001873 T __ZN4zoom4boomERKSs
在C和C ++本地(自动)变量产生任何符号,但是住在寄存器或堆栈。
In both C and C++ local (automatic) variables produce no symbols, but live in registers or on stack.
局部变量没有在生成的目标文件中仅原因,链接器并不需要知道他们的名字。因此,没有名字,没有截断。其他(即链接器看)一切都是名称错位在C ++中。
Local variables do not have names in resulting object file for mere reason that linker does not need to know about them. So no name, no mangling. Everything else (that linker has to look at) is name-mangled in C++.
这篇关于有关名称使用C重整问题++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!