Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, main need not be a function?

Tags:

c

main

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:

  1. In listing 1, linker should have complained for missing "main". Why is it looking for _WinMain@16?

  2. The executable generated from listing 2 simply crashes. What is the reason?

Thanks for your time.

like image 488
Gowtham Avatar asked Feb 12 '10 14:02

Gowtham


People also ask

Does C need a main function?

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.

Can a function run without main?

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.

Can we run a program without main () function in C?

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.

What is a main function in C?

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.


2 Answers

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.

like image 103
Tronic Avatar answered Oct 23 '22 06:10

Tronic


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.

like image 24
Richard Pennington Avatar answered Oct 23 '22 06:10

Richard Pennington