程序编译错误

时间:2014-12-05 07:00:38

标签: c gcc

这个程序违背了我在C中教过和学过的所有内容。这是如何编译的?为什么这不需要是int main?为什么不返回0?你不需要在main上面初始声明sub()吗?这让我不知所措。我喜欢把我的功能放在主要的上面。

#include <stdio.h>

main()
{
   sub ();
   sub ();
}

sub()
{
   static int y = 5;
   printf(" y is %d \n",y);
   y++;
}

gcc版本是:

gcc version 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)

这是旧版本,但似乎并不疯狂。

https://www.gnu.org/software/gcc/releases.html

如何检查这是c90还是c89?

3 个答案:

答案 0 :(得分:4)

此代码使用早期C的一个过时特性,称为 implicit int 。它的唯一用途是在代码 - 高尔夫比赛中。实际上,即使是变量也可以这种方式声明。变量 y 可能很容易被声明为

static y = 5;

可以在没有原型的情况下调用函数。假定该函数准确接收传递的参数数量,受“常规促销”的约束。任何小于int的类型都会提升为int,并且浮点数会提升为double

因此,函数表现为,好像它们的原型为:

int main(void);
int sub(void);

要返回int以外的任何类型,必须指定返回类型。


您可以指定编译时要使用的标准。

gcc -ansi
gcc -std=c99

并添加-pedantic以使gcc相信你的确意味着它。


奇怪的是,这段代码并不严格符合任何标准。 C99禁止隐式int,但允许从return 0;中删除main。 C90或“ansi”C允许隐式int,但需要return。所以,肯定会有回报。

不过,C89和C90完全一样。世界上两个半球都需要一段时间才能达成一致。时区和经络等。这是相同的标准。

答案 1 :(得分:1)

它无法编译。如果你不告诉gcc是一个严格符合C编译器但只是用gcc test.c调用它,那么它将仍然是一个完全非标准的编译器,它允许很多奇怪的东西。当保留默认设置时,它不符合任何已知的C标准。

gcc -std=c11 -pedantic-errors给出:

test.c:3:1: error: return type defaults to 'int'
 main()
 ^
test.c: In function 'main':
test.c:5:4: error: implicit declaration of function 'sub' [-Wimplicit-function-d
eclaration]
    sub ();
    ^
test.c: At top level:
test.c:9:1: error: return type defaults to 'int'
 sub()
 ^
test.c: In function 'sub':
test.c:14:1: warning: control reaches end of non-void function [-Wreturn-type]
 }

答案 2 :(得分:0)

@lundin,请注意:

main()

不等于

int main(void)

因为void表示没有参数,但()表示可以有任意数量的参数。

相关问题