4 ms·
Why do some languages require a main function? I started out with JavaScript decades ago, and of course JS doesn't require a main function. When I started learn
by irrational 6y ago
Why do some languages require a main function? I started out with JavaScript decades ago, and of course JS doesn't require a main function. When I started learning Java I thought the requirement that there must be a main function was just bizarre. I still feel that way, it just feels wrong.
- kibwen 6y agoYou've seen in Java how the main function has the `args` parameter as input, an approach which originally comes from C. In C code, main is actually not the first code that gets run during the program; a compiler-provided shim function called "start" sets up the environment, which includes creating the `args` array, and then calls main and passes args in as a parameter to main. The start function needs something to call, and args needs to come from somewhere; having an explicit main function with an args parameter isn't the only way to achieve this, but it's not a bad way by any means.
- deleted 6y ago[deleted]
- wruza 6y agoBecause languages that compile to a platform binary must obey rules of a system linker and a corresponding stdlib. Javascript is an active host for an entire js program, but C compiler is not. C source files turn into object files (.o/.obj and then .so/.dll for libraries) that have a particular format and may be linked with object files and libraries from other languages. A system linker then decides where the entry point is by looking in every object file for a _start symbol, which is usually implemented by clib, and it basically does: void _start(void) { extern int main(...); init_clib(); exit(main(...)); } The exact procedure heavily depends on a build target. Also, C compiler cli tool (e.g. gcc) is usually a frontend for a compiler and a linker, among other tools, which may add to the confusion. Object files are collections of symbols, either external, or defined in that file. Every non-extern symbol is a region (addr, len) with either data or code. There is no unnamed/main symbols by design. In theory, C could abstract that and allow code at column zero, but there is no rationale for that.
- ballenf 6y agoIf javascript had one (or if Node had one), wouldn't top-level await be unnecessary?