C++ main 的正确声明是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4207134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:50:28  来源:igfitidea点击:

What is the proper declaration of main?

c++mainc++-faq

提问by fredoverflow

What is the proper signature of the mainfunction in C++? What is the correct return type, and what does it mean to return a value from main? What are the allowed parameter types, and what are their meanings?

mainC++ 中函数的正确签名是什么?什么是正确的返回类型,从 返回值是什么意思main?允许的参数类型是什么,它们的含义是什么?

Is this system-specific? Have those rules changed over time? What happens if I violate them?

这是系统特定的吗?这些规则是否随着时间的推移而改变?如果我违反了他们会怎样?

回答by James McNellis

The mainfunction must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

main函数必须在全局命名空间中声明为非成员函数。这意味着它不能是类的静态或非静态成员函数,也不能放在命名空间(甚至是未命名的命名空间)中。

The name mainis not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

main除了作为全局命名空间中的函数外,该名称在 C++ 中不保留。您可以自由声明名为 的其他实体main,其中包括类、变量、枚举、成员函数和不在全局命名空间中的非成员函数。

You can declare a function named mainas a member function or in a namespace, but such a function would not be the mainfunction that designates where the program starts.

您可以将函数声明main为成员函数或命名空间,但这样的函数不会是main指定程序开始位置的函数。

The mainfunction cannot be declared as staticor inline. It also cannot be overloaded; there can be only one function named mainin the global namespace.

main函数不能声明为staticor inline。它也不能过载;main全局命名空间中只能命名一个函数。

The mainfunction cannot be used in your program: you are not allowed to call the mainfunction from anywhere in your code, nor are you allowed to take its address.

main函数不能在您的程序中使用:您不能main在代码的任何位置调用该函数,也不能获取其地址。

The return type of mainmust be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare mainwith a return type of void; this is probably the most frequently violated rule concerning the mainfunction).

的返回类型main必须是int。不允许使用其他返回类型(此规则以粗体显示,因为看到声明main返回类型为 的错误程序很常见void;这可能是有关main函数的最常违反的规则)。

There are two declarations of mainthat must be allowed:

main必须允许有两个声明:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

(1) 中,没有参数。

In (2), there are two parameters and they are conventionally named argcand argv, respectively. argvis a pointer to an array of C strings representing the arguments to the program. argcis the number of arguments in the argvarray.

(2) 中,有两个参数,它们通常分别命名为argcargvargv是一个指向表示程序参数的 C 字符串数组的指针。argcargv数组中的参数数量。

Usually, argv[0]contains the name of the program, but this is not always the case. argv[argc]is guaranteed to be a null pointer.

通常,argv[0]包含程序的名称,但情况并非总是如此。 argv[argc]保证为空指针。

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2)and they both mean exactly the same thing:

请注意,由于数组类型参数(如char*[])实际上只是变相的指针类型参数,因此以下两种都是有效的写法(2)并且它们的含义完全相同:

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

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

一些实现可能允许其他类型和数量的参数;你必须检查你的实现的文档,看看它支持什么。

main()is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a returnstatement in main(): if you let main()return without an explicit returnstatement, it's the same as if you had written return 0;. The following two main()functions have the same behavior:

main()预计返回零表示成功,非零表示失败。您不需要在 中显式地编写return语句main():如果main()没有显式return语句就让return ,则与编写return 0;. 以下两个main()函数具有相同的行为:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESSand EXIT_FAILURE, defined in <cstdlib>that can also be returned from main()to indicate success and failure, respectively.

有两个宏,EXIT_SUCCESSEXIT_FAILURE,定义在其中<cstdlib>,也可以分别返回main()表示成功和失败。

The value returned by main()is passed to the exit()function, which terminates the program.

返回的值main()传递给exit()函数,该函数终止程序。

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main()function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

请注意,所有这些仅适用于为托管环境(非正式地,具有完整标准库且有操作系统运行程序的环境)进行编译时。也可以为独立环境(例如,某些类型的嵌入式系统)编译 C++ 程序,在这种情况下,启动和终止完全由实现定义,main()甚至可能不需要函数。但是,如果您正在为现代桌面操作系统编写 C++,那么您正在为托管环境进行编译。

回答by liaK

From Standard docs., 3.6.1.2 Main Function,

来自标准文档,3.6.1.2 Main Function

It shall have a return type of type int, but otherwise its type is implementation-defined.All implementations shall allow both of the following definitions of main:

它应该有一个 int 类型的返回类型,否则它的类型是实现定义的。所有实现都应允许以下两个 main 定义:

int main() { / ... / }and int main(int argc, char* argv[]) { / ... / }

int main() { / ... / }int main(int argc, char* argv[]) { / ... / }

In the latter form argcshall be the number of arguments passed to the programfrom the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....

后一种形式argc应是从程序运行的环境传递给程序的参数数量。如果 argc 非零,这些参数应在 argv[0] 到 argv[argc-1] 中作为指向初始值的指针提供以空字符结尾的多字节字符串的字符.....

Hope that helps..

希望有帮助..

回答by M.M

The exact wording of the latest published standard (C++14) is:

最新发布的标准 (C++14) 的确切措辞是:

An implementation shall allow both

  • a function of ()returning intand

  • a function of (int, pointer to pointer to char)returning int

as the type of main.

一个实现应允许

  • ()返回函数int

  • 的函数(int,指向char)返回指针的指针int

作为 的类型main

This makes it clear that alternative spellings are permitted so long as the type of mainis the type int()or int(int, char**). So the following are also permitted:

这清楚地表明,只要 ofmain的类型是 typeint()或,则允许使用其他拼写int(int, char**)。因此,以下情况也是允许的:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)
  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

回答by stonemetal

The two valid mains are int main()and int main(int, char*[]). Any thing else may or may not compile. If maindoesn't explicitly return a value, 0is implicitly returned.

两个有效的电源是int main()int main(int, char*[])。任何其他东西可能会或可能不会编译。如果main没有显式返回值,则隐式返回0

回答by Ben Voigt

Details on return values and their meaning

有关返回值及其含义的详细信息

Per 3.6.1 ([basic.start.main]):

根据 3.6.1 ( [basic.start.main]):

A return statement in mainhas the effect of leaving the mainfunction (destroying any objects with automatic storage duration) and calling std::exitwith the return value as the argument. If control reaches the end of mainwithout encountering a returnstatement, the effect is that of executing

return 0;

中的 return 语句main具有离开main函数(销毁任何具有自动存储持续时间的对象)并std::exit以返回值作为参数调用的效果。如果控制到达结束而main没有遇到return语句,则效果是执行

return 0;

The behavior of std::exitis detailed in section 18.5 ([support.start.term]), and describes the status code:

的行为std::exit在 18.5 ( [support.start.term])节中有详细说明,并描述了状态代码:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

最后,控制权返回给宿主环境。如果 status 为零或EXIT_SUCCESS,则返回状态成功终止的实现定义形式。如果 status 是EXIT_FAILURE,则返回状态不成功终止的实现定义形式。否则返回的状态是实现定义的。