C主程序函数为什么可以codeD带或不带参数? [英] Why can C main function be coded with or without parameters?

查看:158
本文介绍了C主程序函数为什么可以codeD带或不带参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道为什么这个

int main(void){}

编译和链接

也是如此这样的:

int main(int argc, char **argv){}

为什么没有它是一个或另一个要求?

Why isn't it required to be one or the other?

GCC甚至会编译和链接一个参数:

gcc will even compile and link with one argument:

int main(int argc){}

但发行与-Wall这样的警告:

but issue this warning with -Wall:

smallest_1.5.c:3:1: warning: ‘main’ takes only zero or two arguments [-Wmain]

我不要求本作中怎么来的,他们允许这样做?但如在如何调用者和被链接器处理主多种可能性?

I am not asking this as in "how come they allow this?" but as in "how does the caller and the linker handle multiple possibilities for main?"

推荐答案

我正在一个Linux的观点如下。

函数在标准清晰度非常特殊的(托管于C11实现)。 //铿锵:的 GCC 和放大器闻名。 llvm.org/相对=nofollow>锵/ LLVM 的....),其中有具体的code处理(并给予你这个警告)。顺便说一句,海湾合作委员会(由 GNU libc的头直通的函数属性)也特别code为的printf 。你可以添加自己的自定义使用GCC的 MELT 为自己的功能属性。

The main function is very special in the standard definition (for hosted C11 implementations). It is also explicitly known by recent compilers (both GCC & Clang/LLVM....) which have specific code to handle main (and to give you this warning). BTW, GCC (with help from GNU libc headers thru function attributes) has also special code for printf. And you could add your own customization to GCC using MELT for your own function attributes.

对于连接往往是一个通常的象征,但它是从信息crt0 称为(编译$ C使用$ C 的gcc -v 来了解什么是真正的意思)。顺便说一句,在 LD(1)连接器(和的 ELF 文件,例如的 目标文件的可执行文件的)没有概念的类型和函数签名和仅涉及名称(这就是为什么C ++编译器做一些名称重整

For the linker, main is often a usual symbol, but it is called from crt0 (compile your code using gcc -v to understand what that really means). BTW, the ld(1) linker (and ELF files, e.g. executables or object files) has no notion of types or function signatures and deals only with names (This is why C++ compilers do some name mangling).

ABI 和的呼叫是如此定义的约定未使用的传递参数​​的函数(如甚至的打开(2) ...)不会做任何伤害(几个参数得到在寄存器中传递)。阅读的x86-64系统V ABI 了解详情。

And the ABI and the calling conventions are so defined that passing unused arguments to a function (like main or even open(2)...) does not do any harm (several arguments get passed in registers). Read the x86-64 System V ABI for details.

又见这个答案。

最后,你真的要切实定义你的 INT主(INT ARGC,字符** argv的)而不是其他的,你希望应该处理计划参数直通他们(至少 - 帮助&放大器; - 版本通过的 GNU编码标准的)。在Linux上,我的的程序(和我诅咒他们的程序员)不这样做(这样的的句柄 - 帮助 &安培; - 版本

At last, you really should practically define your main as int main(int argc, char**argv) and nothing else, and you hopefully should handle program arguments thru them (at least --help & --version as mandated by GNU coding standards). On Linux, I hate programs (and I curse their programmers) not doing that (so please handle --help & --version).

这篇关于C主程序函数为什么可以codeD带或不带参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆