Pass only one argument to main() in C

2019-06-14 01:54发布

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);
}

标签: c gcc main
2条回答
SAY GOODBYE
2楼-- · 2019-06-14 02:36

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.

查看更多
一夜七次
3楼-- · 2019-06-14 02:36

As per the C standard

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

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

If an implementation defines it to accept a single parameter, then it can.

查看更多
登录 后发表回答