Search code examples
cprogram-entry-pointc89

Redefining main to another name


In C90, can I redefine main and give it another name, and possibly add extra parameters using #define?
Have this in a header file for example:

#include <stdio.h>
#include <stdlib.h>
#define main( void ) new_main( void )

int new_main( void );

The header doesn't show any errors when compiling. When I try compiling it with the main C file, however, I keep getting an error

In function '_start': Undefined reference to 'main'     

Solution

  • No, you cannot do that, because it would be against language and OS standards. The name main and its arguments argc, argv and environ constitute a part of system loader calling conventions.

    A bit simplifying explanation (no ABI level, just API level) ensues. When your program has been loaded into memory and is about to start, the loader needs to know which function to call as an entrypoint, and how to pass its environment to it. If it was be possible to change the name of main and/or its parameter list, it would have been needed to communicate details of new calling interface back to the loader. And there is no convenient way to do it (apart from writing your own executable loader).

    In function '_start': Undefined reference to 'main'
    

    Here you can see an implementation detail of Linux/POISX ELF loader interface. The compiler adds function _start to your program behind the scenes, which is an actual program entrypoint. _start is tasked to do extra initialization steps common to most programs that use LibC. It is _start that later calls your main. Theoretically, you could write a program that has its own function called _start and no main and it would be fine. It is not trivial as you will have to make sure that the default _start code is no longer being attached to your program (no double definitions), but it is doable. And no, you cannot choose other name than _start for the same reasons.