Home > Blockchain >  Does the main function have to be called main?
Does the main function have to be called main?

Time:08-19

In C, can the main function be called something else? Is there something special about the name, "main," or is it arbitrary?

CodePudding user response:

Is there something special about the name main or is it arbitrary?

The name, "main," for the entry point of a C program (in a hosted environment) is not arbitrary but is defined by the C Standard:

5.1.2.2.1 Program startup

1      The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
    int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
    int main(int argc, char *argv[]) { /* ... */ }

In C can the main function be called something else?

Most mainstream toolchains used to compile/build C programs do offer ways to use other names for the entry-point procedure: typically, a linker option explicitly specifying the name, as outlined here. However, such programs do not strictly conform to the C Standard and may cause portability issues, as indicated in "Annexe J" of the cited draft C Standard:

J.3 Implementation-defined behavior


J.3.2 Environment

    — The name and type of the function called at program startup in a freestanding environment
    — An alternative manner in which the main function may be defined

CodePudding user response:

C allows two forms of systems: freestanding and hosted. A freestanding system is a program without an OS, a program running on a RTOS or the OS itself. A hosted system is something where programs are running on top of an OS such as Linux or Windows.

In freestanding systems, the name and form of the function called when the program starts is compiler-specific. They may use int main (void) or something else entirely. Most common is void main (void).

In hosted systems, two standardized forms exist: int main (void) and int main (int argc, char* argv[]). The standard does however, subjectively, allow implementation-defined forms as well.

What's important to realize is that the form of main() or equivalent is always decided by the compiler and never by the programmer. Programmers cannot use forms that are not documented as valid by the compiler.

Furthermore, a program which is strictly conforming = no compiler-specific behavior, may only use either
int main (void) or
int main (int argc, char* argv[]).

int main (void) is special since it is the only function that may be written without an explicit return and still return 0. Also, returning from main() is equivalent to calling the exit() function.

Details here: https://stackoverflow.com/a/31263079/584518

  • Related