c++ - 为什么 C 和 C++ 中的 main 函数的类型留给用户定义?

标签 c++ c program-entry-point

为什么 main() 是用户定义的函数?

什么时候使用 void main()int main()

最佳答案

编辑这个答案并不完整,因为它并没有真正解决奇怪的句子“或以某种实现定义的方式”。我现在写了一个more complete answer它还涉及 C90、C11 和 C++。 编辑结束

以下是 C 标准 (ISO C 9899:1999):

5.1.2.1 Freestanding environment

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. / .. / The effect of program termination in a freestanding environment is implementation-defined.

5.1.2.2 Hosted environment

A hosted environment need not be provided, but shall conform to the following specifications if present.

5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

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

C++ 标准中的文本或多或少是相同的。 注意文本中的“程序启动”是托管环境的子条款

这意味着:

  • 如果您的程序在无主机环境中运行(您的程序是嵌入式系统或操作系统),它可能有任何返回类型。 void main() 是最常见的。

  • 如果您的程序在托管环境中运行(在操作系统之上),main() 必须返回 int,并且可能有其他参数。

关于c++ - 为什么 C 和 C++ 中的 main 函数的类型留给用户定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5296163/

相关文章:

c++ - Cygwin GCC 与 Visual Studio 库链接

c++ - 使用Nsight调试导出DLL的非启动项目中的CUDA代码

c++ - 使用 rapidjson 读取子对象 vector

c - pragma weak 的支持有多广泛,它是否克服了使用 gcc 属性的问题?

c - [curl lib]如何获得响应/重定向 url?

c - 对符号 'CERT_GetDefaultCertDB@@NSS_3.2' 的 undefined reference

java - 无法引用已声明的对象字段

C++ 在 scanf() 读取结果导致进程终止后删除指针

java - 具有多个 main 的 Jar

C++:main() 未捕获的异常的自定义格式