简体   繁体   English

将main声明为extern“C”是合法的C ++吗?

[英]Is it legal C++ to declare main as extern “C”?

Being a low-level programmer, I often work with the module startup code for executables, so I understand pretty well how code like "crt0" work. 作为一个低级程序员,我经常使用可执行文件的模块启动代码,所以我很清楚像“crt0”这样的代码是如何工作的。 When writing C++ code, I've generally declared main as extern "C" to match what the C startup code is going to do to call main . 在编写C ++代码时,我通常将main声明为extern "C"以匹配C启动代码要调用main I thus usually use this declaration for main (and wmain if specifically targeting Windows): 因此我通常将此声明用于main (如果专门针对Windows,则使用wmain ):

extern "C" int main(int argv, const char *const *argv)

extern "C" int __cdecl wmain(int argv, const wchar_t *const *argv)

Is it legal to use extern "C" on main ? main使用extern "C"是否合法? Also, is const char *const * legal for argv's type as opposed to char *[] ? 另外, const char *const *对于argv的类型是合法的而不是char *[]

The linkage is implementation defined (3.6.1p3): 链接是实现定义的(3.6.1p3):

The linkage (3.5) of main is implementation-defined. main的链接(3.5)是实现定义的。

Also, for your latter question, that is perfectly acceptable to have const char* const* (3.6.1p2): 另外,对于后一个问题,使用const char* const* (3.6.1p2)是完全可以接受的:

An implementation shall not predefine the main function. 实现不应预定义主函数。 This function shall not be overloaded. 此功能不应过载。 It shall have a return type of type int, but otherwise its type is implementation-defined. 它应该具有int类型的返回类型,否则其类型是实现定义的。

The standard blesses two forms of main : 标准祝福两种形式的main

int main()
int main(int argc, char* argv[])

These forms are what any implementation must recognize. 这些表单是任何实现必须识别的。 Everything else is your implementation being easy with your code and letting you be creative. 其他任何事情都可以通过您的代码轻松实现,让您充满创意。 It is not illegal, as the standard specifically allows it to recognize other forms of main . 这不是非法的,因为标准特别允许它识别其他形式的main

The startup code is normally written in a way that allows it to call main having no linkage declaration, because that's how the standard says main should be. 启动代码通常以允许它调用main的方式编写,没有链接声明,因为这就是标准main应该如何。 The compiler usually treats main specially as having C linkage, as allowed by the standard, so that's how the startup code declares it. 编译器通常将main特别视为具有C链接,如标准所允许的那样,因此启动代码如何声明它。 This is of no interest to a normal programmer. 这对普通程序员来说并不重要。 He just needs to follow the standard. 他只需要遵循标准。

extern "C" only tells the C++ compiler specifically to NOT decorate or use name wrangling on generated function labels. extern "C"只告诉C ++编译器没有在生成的函数标签上进行装饰或使用名称争用。

Yes, both are legal. 是的,两者都是合法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM