In C, main need not be a function?

2019-03-12 19:15发布

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.

标签: c main
8条回答
何必那么认真
2楼-- · 2019-03-12 20:10

Case 1. is Windows-specific - the compiler probably generates _WinMain symbol when main is properly defined.

Case 2. - you have a pointer, but as static variable it's initialized to zero, thus the crash.

查看更多
老娘就宠你
3楼-- · 2019-03-12 20:14

1.) An (compiler/platform) dependent function is called before code in main is executed and hence your behavior(_init in case of linux/glibc).
2) The code crash in 2nd case is justified as the system is unable to access the contents of the symbol main as a function which actually is a function pointer pointing to arbitrary location.

查看更多
登录 后发表回答