void main() { } 无需头文件即可完美运行。怎么会这样,用C写的main函数的定义在哪里?

void main() { } works perfectly without a header file. How can this happen ,where is the definition of main function written in C?

我写了下面的代码:

void main() {

}

怎么能运行没有任何头文件呢?

如果您在没有 header 的代码中使用 printf,编译器不知道您指的是什么类型的实体。

如果您提供 main 实现 ,编译器确切地知道这是什么意思,您只是指定了它。

void 是编译器已知的 built-in 类型。 main 是程序的入口点,而 printf,如您所写,需要一些原型。如果您在源代码中编写自己的 printf 定义,它将在没有 header.

的情况下编译

编译 C 程序唯一要做的就是指定一个入口点,即 main

header只是提供其他 IO 可能性。

void printf()
{

}

int main()
{
    printf();
}

来自 C 标准(5.1.2.2.1 程序启动)

1 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[]) { /* ... */ }

or equivalent;10) or in some other implementation-defined manner.

虽然一些编译器,例如 MS VS 的编译器支持 return 类型 void 函数 main 的声明,但是这样的声明不是函数 main 的 C 标准声明.

因此,由于实现没有声明函数 main 的原型,并且如果函数 main 不调用任何其他函数,则都不需要 header。

你可以写

int main( void )
{
}

return 语句也可以省略。

注意是用户定义了main函数。所以在上面给出的程序中有一个函数 main 的定义,它的 body 中不包含任何语句。该函数不执行任何操作,并且立即 return 控制托管环境。

头文件只是一种语言功能,它提供了在不同模块(翻译单元)甚至整个库中组织代码的方法。它们绝不是强制使用的。

在 C 程序中唯一必须做的事情就是要有某种方式的程序入口点。在托管系统(例如具有 OS 的 PC)上,此入口点必须是名为 main() 的函数。它可以通过多种方式声明。 void main() 不能保证工作,除非编译器明确支持该形式。最便携和标准化的格式是:

int main (void)
{
  return 0;
}

现在当然这个程序对 运行 来说不是很令人兴奋,因为它什么都不做。但它是完全有效的。

不需要任何 main() 的前向声明。对于独立环境,入口点的格式完全由实现定义。对于托管环境,C 标准明确指出 "The implementation declares no prototype for this function." - 在这种情况下的实现意味着编译器。在英语中,根据语言定义,main() 函数必须在没有任何先前声明的情况下简单地工作。

Details regarding the various allowed forms of main().