This code compiles, but no surprises, it fails while linking (no main found):
Listing 1:
void main();
Link error: \mingw\lib\libmingw32.a(main.o):main.c:(.text+0x106) undefined reference to _WinMain@16'
But, the code below compiles and links fine, with a warning:
Listing 2:
void (*main)();
warning: 'main' is usually a function
Questions:
In listing 1, linker should have complained for missing "main". Why is it looking for _WinMain@16?
The executable generated from listing 2 simply crashes. What is the reason?
Thanks for your time.
c does not require a main() function. Show activity on this post. main is mandatory to be present if you are building your code into an application as main functions serves as an entry point for the application. But, if your code is being built as lib, then main is not needed.
yes it is possible to write a program without main(). But it uses main() indirectly. The '##' operator is called the token pasting or token merging operator.
So actually C program can never run without a main() . We are just disguising the main() with the preprocessor, but actually there exists a hidden main function in the program.
A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. A main() function is used to invoke the programming code at the run time, not at the compile time of a program.
True, main
doesn't need to be a function. This has been exploited in some obfuscated programs that contain binary program code in an array called main
.
The return type of main() must be int
(not void
). If the linker is looking for WinMain
, it thinks that you have a GUI application.
In most C compilation systems, there is no type information associated with symbols that are linked. You could declare main as e.g.:
char main[10];
and the linker would be perfectly happy. As you noted, the program would probably crash, uless you cleverly initialized the contents of the array.
Your first example doesn't define main, it just declares it, hence the linker error.
The second example defines main, but incorrectly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With