Compiling with int main(void) fails; main(int argc, char *argv[]) succeeds. Why?

▼魔方 西西 提交于 2019-12-18 06:25:56

问题


Problem

Why would compiling a program which has an int main(void) main function differ from compiling a program which has an int main(int argc, char *argv[]) main function, if the program does not use arguments passed on the command line?

Is this OS or compiler specific? I do not get the same results using mingw and g++(which is weird isn't it as wingw is a port of gcc).


Example

Code

#include <iostream>
#include"SDL/SDL.h"
int main(void)
{
    return 0;
}

Compilation commands

g++ test.cpp; #g++ 4.4.5
i586-mingw32msvc-g++ test.cpp; # mingw 4.4.4

Error

(Given by the second command.)

a(main.o):(.text+0x85): undefined reference to `_WinMain@16'

回答1:


This is SDL thing. On Windows, when you include SDL.h,main is redefined to SDL_main which calls WinMain (the real entry point in non-console Windows apps), does some initialization and finally calls your main code. It has a signature with argc and argv and you're pretty much required to follow it, so int main() won't work.




回答2:


The specification of main(...) is a contract. In the C language, the contract says that the arguments are int and char **. This is a requirement your program has to fulfill, if it wants the environment to interact with it.

Whether or not your program wants to use the parameters is a different issue -- it just has to abide by the contract that there is a functiona named main, with the correct order and type of parameters.



来源:https://stackoverflow.com/questions/8673378/compiling-with-int-mainvoid-fails-mainint-argc-char-argv-succeeds-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!