Write a C/C++ program without using the 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 occur without the benefit of an operating system, the starting point needs not to be main(). An OS kernel or embedded system environment would be a good example of a freestanding environment.

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

So, we can say that main() is the entry point for your program from a programmer’s 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 using the -nostartfiles option.

2. Using Static Initializer in C++

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

Download  Run Code

Output:

Inside execute()

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

Download  Run Code

Output:

Inside Constructor

3. Using Macro Arguments

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

Download  Run Code

Output:

Hello World