c++ - main() 的函数类型

标签 c++ c

main 是用户定义函数还是内置函数?或者两者兼而有之?

如果我说 main 的声明是预定义的而定义是用户定义的,我可以说它既是内置的又是用户定义的吗?

这里有一个讨论: Is main() a User-Defined Function?

但我无法理解他们得出的结论,或者确切地说,我对答案并不满意。我与上面关于无法调用 main 的链接的讨论不同。它可以被调用,但不应该被调用(如果这个概念是错误的请纠正我!)。

最佳答案

C11 标准列出了两种环境:独立环境t,意思是嵌入式系统或操作系统,以及托管环境,意思是程序运行在操作系统。

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.

换句话说,在独立环境中,启动时调用的函数可以被称为任何东西,并具有任何形式。最常见的是 void main (void)

从 C11 开始,关于托管环境的章节:

5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no prototype for this function.

“实现”指的是编译器,所以编译器没有声明这样的函数。这样做取决于用户(程序员)。这可以以 int main (void)int main(int argc, char *argv[]) 或编译器指定的任何实现定义的方式完成.在任何情况下,该功能都是由用户定义的。

C++ 稍微严格一点,强制执行这两种形式中的任何一种,并且不允许 main 的实现定义版本。从 C++03 3.6.1 开始:

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. All implementations shall allow both of the following definitions of main:

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

and

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


关于是否可以调用 main:我认为 C 标准中没有任何内容可以阻止这种情况,即使调用 main 毫无意义。由于它没有原型(prototype),调用它的唯一方法是递归,这很愚蠢,但很有可能。

在 C++ 中,C++03 和更高版本的标准明确禁止调用 main():

The function main shall not be used (3.2) within a program. The linkage (3.5) of main is implementation-defined. A program that declares main to be inline or static is ill-formed.

关于c++ - main() 的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27419071/

相关文章:

C - 如何获取 Char 中的 4 个最低有效位

c++ - 如何在 GCC 4.5 中使用 C++0x 原始字符串?

c++ - CLucene 中的内存泄漏

c++ - C++ 中 strcpy_s 的复杂性

字符数组赋值

c - 使用 Autotools 对 `main' 的 undefined reference

c++ - 使用 BOOST_FOREACH 修改 std::vector 中的指针

c++ - 为什么以下代码中的输出停止在 0?

c - 将 Doxygen 链接类型用于 C 文件

c - 如何缓解此代码中的整数溢出?