knowledge
knowledge

Reputation: 1025

main function in c - program termination success or failure

As far as I understand if the main function returns 0 this indicates always successful program termination. Even if success is indicated by another int value.

If main returns a non-zero value it is implementation specific if this stands for unsuccessful program termination or another error code

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.)

So only success is defined in the C standard (return 0) and not how a non-zero int value is interpreted, right? E.g. if in a certain system 1 stands for "success" return 0 would be deliver 1 as well? How is this done?

Upvotes: 1

Views: 1243

Answers (1)

user3386109
user3386109

Reputation: 34829

The main function is the entry point to your code, it is not the entry point to the executable. The executable contains an operating-system defined entry point, that runs some startup code before calling main.

main is called from the startup code just like a normal function. The return value from main is received by the startup code, which can perform any translations necessary to conform to the requirements of the operating system.

The startup code is specific to each operating system. Operating systems have requirements concerning the operation and environment of executables. The C language has requirements concerning the environment that the C code runs in (specifically the arguments to main and the return value from main). It's the responsibility of the startup code to bridge the gaps between those two sets of requirements.

The startup code is delivered as an object file, commonly called "crt.o", short for "C runtime". That file is included in the executable by the linker. You can find the actual name of that file by examining the linker command line. The startup file is typically the first file on the linker command line.

Upvotes: 2

Related Questions