Write a C Program without using main function

Write a C or C++ program without using main function. We are allowed to change the entry point of the program from main() to any other function or remove the main() function altogether.


1. Using GCC _start function


As per C/C++ standard, main() is the starting point of any program in a hosted environment where a program uses the facilities of an operating system. But in a freestanding environment, where a program execution may take place without the benefit of an operating system, the starting point need not be main(). An OS kernel or embedded system environment would be good example of a freestanding environment.

It is worth pointing out that there are whole lot of other things that happens before main() function is executed. i.e. main() is not the first entry point of the program. If you’re using GCC, _start function is the entry point of a C program which makes a call to main(). The main job of _start function is to perform a few initialization tasks.

So we can say that main() is the entry point for your program from a programmers perspective and _start is the usual entry point from the Operating System perspective. We can override _start and ask the compiler for full control over what is happening right from the start by using "-nostartfiles" option.




2. Using static initializer


We can also use a static initializer to call any custom function before main is executed and we can use exit() function inside that custom function, so program will terminate and control will never reach the main() function.


Download   Run Code


Inside execute()


We can also make use of C++ class constructor to do the same.


Download   Run Code


Inside Constructor




3. Using Macro Arguments


The ## macro operator concatenates two separate tokens together to form a single token. Below function uses ## macro operator to hide main method. But the code still does make call to the main function behind the scenes, but just not in plain sight.


Download   Run Code


Hello World

Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of