在C中只传递一个参数给main() [英] Pass only one argument to main() in C

查看:701
本文介绍了在C中只传递一个参数给main()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux上使用GCC(gcc版本4.8.4(Ubuntu 4.8.4-2ubuntu1〜14.04.3))运行此程序。它使用 gcc myprog.c 成功编译,并且运行时没有任何警告或错误。 所以,为什么编译器只给一个参数 main 提供任何警告或错误c> in C?

  #include  

int main(int i)
{
printf(%d \ n,i);


$ b $ div
解析方案/ Debian / Sid / x86-64)我的编译器在编译时使用 gcc -Wall rsp.c -o rsp 您的 rsp.c example。

  rsp.c:3:5:warning:'main'只有零或两个参数[-Wmain] 
int main(int i)
^ ~~~

但是,C11的编程语言(读 n1570 )不指定编译器何时发出警告。它主要定义什么是正确的可能的程序,它们应该如何表现。阅读更多关于未定义的行为(我想,但我不确定是否有) 。



如果您想真正理解您的计算机上实际发生的情况,请研究编译器的源代码,发出的汇编代码(使用 gcc -S -fverbose -asm -O rsp.c 然后查看生成的 rsp.s ),源代码您的 C标准库。 org / wiki / Crt0rel =nofollow noreferrer> crt0 运行时。研究还 ABI 和所述调用约定与您的系统相关。



我认为您应该非常害怕未定义的行为。非常不好的事情可能发生



作为一个实用的建议,当在Linux上进行编码,总是使用 -Wall -g 传递给 gcc
-Wall 选项几乎要求所有警告(您可以添加 -Wextra )。 -g 选项要求提供调试信息。然后,您可以使用 gdb 调试器来了解更多在运行时发生的事情。



一旦你对你的代码有信心并且已经调试过了,考虑用 -O -O2 来编译它以请求优化(特别是基准测试)。 (顺便说一句, gcc 可以接受 -g -O2 )。阅读有关 GCC命令选项的文档。


I ran this program in GCC(gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)) on Linux. It successfully compiled using gcc myprog.c and run without any warnings or errors.

So, Why doesn't the compiler give any warnings or errors when only one argument is provided for main in C?

#include <stdio.h>

int main(int i)
{
    printf("%d\n", i);
}

解决方案

With GCC 6 (on Linux/Debian/Sid/x86-64) my compiler does give some warning when compiling with gcc -Wall rsp.c -o rsp your rsp.c example.

rsp.c:3:5: warning: ‘main’ takes only zero or two arguments [-Wmain]
 int main(int i)
     ^~~~

But the C11 programming language (read n1570) does not specify when a compiler should warn. It mostly defines what are the correct possible programs and how should they behave. Read more about undefined behavior (I guess, but I am not sure, that you have one).

If you want to really understand what is actually happening in your case on your computer, study the source code of your compiler, the emitted assembler code (compile with gcc -S -fverbose-asm -O rsp.c then look into the generated rsp.s), the source code of your C standard library, of your crt0 runtime. Study also the ABI and the calling conventions relevant to your system.

I think you should be very scared of undefined behavior. Very bad things could happen.

As a practical advice when coding on Linux, always compile with -Wall and -g passed to gcc The -Wall option asks for nearly all warnings (and you could add -Wextra). The -g option asks for debug information. You'll then be able to use the gdb debugger to understand more what is happening at runtime.

Once you are confident in your code and have debugged it, consider compiling it with -O or -O2 to ask for optimization (in particular for benchmarking). (BTW, gcc can accept both -g and -O2). Read documentation on GCC command options.

这篇关于在C中只传递一个参数给main()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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