Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC C99 Disable compilation of main() without return

Tags:

c

gcc

c99

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

like image 405
Den4ik Avatar asked Sep 21 '25 04:09

Den4ik


2 Answers

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.

like image 84
Eric Postpischil Avatar answered Sep 22 '25 20:09

Eric Postpischil


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 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; 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.

like image 31
dbush Avatar answered Sep 22 '25 19:09

dbush