Why name-mangling has no effect on main function in C++?

随声附和 提交于 2021-01-27 05:35:14

问题


C++ compiler often mangle function names to support many features. Programer can suppress default name-mangling using extern "C" way. However, why int main(int, char **) not affected ever?

// test.cpp

int max(int a, int b) {
    return a > b ? a : b;
}

extern "C" {
    int min(int a, int b) {
        return a < b ? a : b;
    }
}

int main (int argc, char *argv[]) {
    return 0;
}    

And

$  xcrun --sdk macosx clang -x c++ -c test.cpp -o test  
$  xcrun nm -nm test  

0000000000000000 (__TEXT,__text) external __Z3maxii  
0000000000000030 (__TEXT,__text) external _min  
0000000000000060 (__TEXT,__text) external _main  

Obviously, int max(int, int) is mangled to __Z3maxii; int min(int int) is free from mangling with extern "C" annotation.

How does main escape from mangling?
Is there any way else to keep name from mangling except the above annotation?


回答1:


Per [basic.start.main]/1, [basic.start.main]/2 and [over]/1:

A program shall contain a global function called main. [...] This function shall not be overloaded. [...] When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded [...].

This is then undefined behavior to have anything in the global namespace with the name main. There is then no reason for an implementation to mangle main or even consider it to be a proper function.




回答2:


Name mangling is a process used by C++ compilers to give each function in your program a unique name. In C++, generally programs have at-least a few functions with the same name ie function overloading, however Main is special, its actually a global function of the C language that can never be overloaded, so it is not necessary.

Take a look at https://en.cppreference.com/w/cpp/language/main_function

And questions about name mangling in C++

(Main) special properties

It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace (since C++17))



来源:https://stackoverflow.com/questions/53393585/why-name-mangling-has-no-effect-on-main-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!