I learned from my colleague that one can write and execute a C program without writing a main()
function. It can be done like this:
my_main.c
/* Compile this with gcc -nostartfiles */
#include <stdlib.h>
void _start() {
int ret = my_main();
exit(ret);
}
int my_main() {
puts("This is a program without a main() function!");
return 0;
}
Compile it with this command:
gcc -o my_main my_main.c –nostartfiles
Run it with this command:
./my_main
When would one need to do this kind of thing? Is there any real world scenario where this would be useful?
The symbol _start
is the entry point of your program. That is, the address of that symbol is the address jumped to on program start. Normally, the function with the name _start
is supplied by a file called crt0.o
which contains the startup code for the C runtime environment. It sets up some stuff, populates the argument array argv
, counts how many arguments are there, and then calls main
. After main
returns, exit
is called.
If a program does not want to use the C runtime environment, it needs to supply its own code for _start
. For instance, the reference implementation of the Go programming language does so because they need a non-standard threading model which requires some magic with the stack. It's also useful to supply your own _start
when you want to write really tiny programs or programs that do unconventional things.