views:

157

answers:

3

Hii ,

We generally see that the program execution begins in the main method for the languages like C , C++ , Java (i am familiar with these). I want to know how the compiler knows the presence of MAIN method in the program .

What does the main method signify besides that it is the entry point for program execution ...How does these criteria differ for C , C++ ...

Provide any links which you think are helpful ...

A: 

On windows it all starts with the Portable Executable file format: http://en.wikipedia.org/wiki/Portable_Executable.

The entry address can be specified through the linker: http://msdn.microsoft.com/en-us/library/y0zzbyt4.aspx

A managed application has a reference to the static main method in its assembly metadata. Again this is a command line option of the compiler: http://msdn.microsoft.com/en-us/library/6s2x2bzy%28v=VS.71%29.aspx

Alex
Thanx for the links
ravi
-1 for supplying a platform-specific answer to a platform-agnostic question
Erick Robertson
+1 because the score of this answer should stay nonnegative.
Alexandre C.
Yay! Alex gains +8 rep for providing a bad answer.
Erick Robertson
+4  A: 

Generally, the code that is executed at the beginning of every C or C++ program (included usually by default by compilers/linkers) does some initialization and then calls a function called main. If this function is not present, it will lead to an unresolved name when linking a program (in which all the names have to be resolved). If it is present, it will be called by the program initialization code.

The initialization code does some housekeeping (for example, converts the return value of the main function to the exit code of the program, etc.)

Diego Sevilla
+1  A: 

Nothing. It's just a conventional name for the starting point of the program.

in C, main() is as normal a function as sin() or any other function. The only requirement in a hosted implementation is that it conforms to one of the prototypes

int main(void);
int main(int, char **);

Edit

You can even call main() yourself from your code :)

#include <stdio.h>
int main(int argc, char **argv) {
    printf("main() called with %d arguments.\n", argc);
    if (argc) {
        main(0, NULL);
    }
    return 0;
}
pmg
As you noted, that's true for C. In C++, `main` is a bit more special; it may not be called directly, must not be overloaded, etc.
jamesdlin
Hmmm, ok. I didn't know that. Thanks for the heads-up :)
pmg