commit cf2d0f641671237b6532bf60623e9c17727c2929
parent 107d871adc180ab9c1d7254e30fc399f3cb259b8
Author: Roberto E. Vargas Caballero <k0ga@shike2.net>
Date: Mon, 30 Mar 2026 12:19:19 +0200
cc1: Add default return 0 in main
C99 specifies that main should return 0 if there is a no explicit return
statement. The simplest solution is to emit always a return 0 at the
end of the main function and let to the control flow analysis to get rid
of it when it is not needed.
Diffstat:
3 files changed, 28 insertions(+), 0 deletions(-)
diff --git a/src/cmd/scc-cc/cc1/decl.c b/src/cmd/scc-cc/cc1/decl.c
@@ -578,6 +578,12 @@ funbody(Symbol *sym, Symbol *pars[])
sym->u.pars = pars;
emit(OFUN, sym);
compound(NULL, NULL, NULL);
+
+ if (strcmp(sym->name, "main") == 0) {
+ emit(ORET, NULL);
+ emit(OEXPR, constnode(zero));
+ }
+
emit(OEFUN, NULL);
popctx();
flushtypes();
diff --git a/tests/cc/execute/0257-main.c b/tests/cc/execute/0257-main.c
@@ -0,0 +1,21 @@
+int
+f2(int c)
+{
+ return c+2;
+}
+
+int
+f1(int a)
+{
+ return a+3;
+}
+
+int
+main(void)
+{
+ int h1 = 5, h2 = 3, h3;
+
+ h3 = f1(h1) + f2(h2);
+ if (h3 != 13)
+ return 1;
+}
diff --git a/tests/cc/execute/scc-tests.lst b/tests/cc/execute/scc-tests.lst
@@ -247,3 +247,4 @@
0254-litchar.c
0255-init.c
0256-ary.c
+0257-main.c