In said:
I have been programming in C for about a year now. It sounds silly,
but I never took the time to question why a C(or C++ or Java) program
execution begins only at the main(). Is it a convention or is there
some deeper underlying reason?
It is a convention between the people who wrote the C startup module and
the people who write C programs. Try to omit the main() function from
a C program and see what happens at link time:
fangorn:~/tmp 108> cat test.c
void foo(){}
fangorn:~/tmp 109> gcc test.c
/usr/lib/crt1.o(.text+0x18): In function `_start':
: undefined reference to `main'
This shows that the module /usr/lib/crt1.o that was automatically linked
to your program was calling main(), but the linker couldn't find that
function. Of course, you can fool most linkers, as they are not
particularly smart:
fangorn:~/tmp 111> cat test.c
int main;
fangorn:~/tmp 112> gcc test.c
fangorn:~/tmp 113>
But running the resulting executable is left for the fool or the brave
(or the foolishly brave ;-)
Note that this convention is valid only for hosted implementations.
Freestanding implementations may use a different convention (there may be
no main function in the kernel of your OS, even if it was written in C).
Dan