How to force gcc compilator throw error when int main() have no return statement. This code compiles without any errors
#include<stdio.h>
int main(){
printf("Hi");
}
I am using
gcc -Wall -Wextra -std=c99 -Wreturn-type -Werror -pedantic-errors a.c
command for compilation
Den4ik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
This can’t be disabled, as such behavior would be in violation of the C99 standard.
Section 5.1.2.2.3 of C99 states the following regarding the main
function:
If the return type of the
main
function is a type compatible withint
,
a return from the initial call to the main function is equivalent to
calling theexit
function with the value returned by themain
function
as its argument; reaching the}
that terminates themain
function
returns a value of 0. If the return type is not compatible withint
,
the termination status returned to the host environment is
unspecified.
You can avoid the special treatment that main
receives by renaming it. Compiling with -Dmain=AlternateName -Werror=return-type
yields “error: control reaches end of non-void function”.
Naturally, you would do this as a special compilation to test for the issue and not use the object module resulting from this compilation. A second normal compilation without -Dmain=AlternateName
would be used to generate the object module.
It is not possible as it correct in C99
5.1.2.2.3 Program termination 1 If the return type of the main function is a type compatible with int, a return from the initial call
to the main function is equivalent to calling the exit function with
the value returned by the main function as its argument; 11) reaching
the } that terminates the main function returns a value of 0. If the
return type is not compatible with int, the termination status
returned to the host environment is unspecified.
2