How to write a C program to print "Hello world" without main() function?
At first, it seems impractical to execute a program without a main() function because the main() function is the entry point of any program.
Let us first understand what happens under the hood while executing a C program in Linux system, how main() is called and how to execute a program without main().
Following setup is considered for the demonstration.
From C/C++ programming perspective, the program entry point is main() function. From the perspective of program execution, however, it is not. Prior to the point when the execution flow reaches to the main(), calls to few other functions are made, which setup arguments, prepare environment variables for program execution etc.
The executable file created after compiling a C source code is a Executable and Linkable Format (ELF) file.
Every ELF file have a ELF header where there is a e_entry field which contains the program memory address from which the execution of executable will start. This memory address point to the _start() function.
After loading the program, loader looks for the e_entry field from the ELF file header. Executable and Linkable Format (ELF) is a common standard file format used in UNIX system for executable files, object code, shared libraries, and core dumps.
Let's see this using an example. I'm creating a example.c file to demonstrate this.
This outputs following critical information of executable on my machine. Have a look at start address below, this is the address pointing to _start() function.
As we can clearly see this is pointing to the _start() function.
The _start() function prepare the input arguments for another function _libc_start_main() which will be called next. This is prototype of _libc_start_main() function. Here we can see the arguments which were prepared by _start() function.
Calls _init() function which performs initialization before the main() function start.
After all the prerequisite actions has been completed, _libc_start_main() calls the main() function.
How to print "GeeksforGeeks" with empty main() in C, C++ and Java?
last_page How does Duff's Device work?