Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

On visual studio, the main() is not the entry point of the program.

The entry point is automatically generated by the compiler, it calls a few functions depending on what the program does then calls the main, I think it had to do with initializing the standard library. You can see the stub using a debugger or a disassembler.

It's possible to set the entry point point to any function name. See advanced project settings.

Now about the arguments and return type. With main the caller is responsible for pushing arguments onto the stack before the call, then popping the stack after the call. the return code is in the EAX register if I remember well.

Because of that, it doesn't matter what's the signature of the main, the invocation will work irrelevant of the arguments.

People may ask what's the point of knowing any of this? One major use case is to write executable compressors like UPX. Another use case is to make a custom entry point written in assembler.



Not just in Visual Studio. main is usually (always?) not the entry point on unixoid systems either, that's much more likely to be _start, which calls main() down the line.

Nevertheless, main is treated specially by the compiler for the aforementioned historical reasons, for example to not warn/error out if it does not return a value despite the type clearly telling so.

Observe:

% echo 'int main(void) { }' > foo.c; clang -c foo.c

<no output>

% echo 'int foo(void) { }' > foo.c; clang -c foo.c

foo.c:1:17: warning: non-void function does not return a value [-Wreturn-type]

int foo(void) { } ^ 1 warning generated.

As you can see, clang is happy to ignore the missing return value for main(), but not for foo().


Also, just as execution doesn't start in main, it also doesn't end with main, either. In C, you can register `atexit` handlers. You can do that in C++, too. In C++, you can also have "user" code executed before & after main by virtue of static initialization & destruction.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: