问题描述
下面是我的代码:
//main.c
//I'm not using header file here,I know it is bad practice, it is just for demo purpose.
int main()
{
func();
return 0;
}
//test.c
void func()
{
...
}
我们可以看到上面的代码可以编译并且可以通过链接器链接,但是同一件事不适用于变量:
we can see that above code compiles and can be linked by linker, but the same thing doesn't apply to variables as:
//main.c
int main()
{
sum += 1;
return 0;
}
//test.c
int sum = 2020;
然后此代码将无法编译且无法链接,我们必须在main.c中的main函数之前添加extern int sum;
.
then this code won't compile and can't be linked, and we have to add extern int sum;
before main function in main.c.
但是为什么我们不需要在main.c
中将extern
添加为:
But why we don't need to add extern
in main.c
as:
//main.c
extern void func(); //or `void func();` since functions are by default external
// without above line, it still compile
int main()
{
func();
return 0;
}
这里有点矛盾吗?
注意:说函数默认是外部的.",我的理解是:我们可以保存一些按键,而无需键入extern
,因此void func(); == extern void func();,但是我们仍然需要在main.c中的main函数之前添加void func();
,对吗?
Note: by saying " Functions are by default external.",my understanding is: we can save some keystokes without typing extern
, so void func(); == extern void func();, but we still need to add void func();
before main function in main.c, isn't it?
推荐答案
由于C99,这两个程序都不正确,并且可能被编译器拒绝.未经事先声明,不得在表达式中使用标识符.
Both programs are incorrect since C99 and may be rejected by the compiler. An identifier may not be used in an expression without previously being declared.
在C89中,有一条规则,如果您编写类似于函数调用的内容,并且以前未声明过函数名称,则编译器将插入函数声明int f();
.对于使用不带括号的其他标识符,没有类似的规则.
In C89 there was a rule that if you write something that resembles a function call, and the function name has not previously been declared, then the compiler inserts a function declaration int f();
. There was not a similar rule for use of other identifiers that aren't followed by parentheses.
即使设置为C99或更高版本,某些编译器(取决于编译器标志)也将发出诊断信息,然后仍然执行C89行为.
Some compilers (depending on compiler flags) will, even if set to C99 or later mode, issue a diagnostic and then perform the C89 behaviour anyway.
注意:由于隐式声明为int func();
,但是函数定义的void func()
是不兼容的类型,因此您的程序仍会在C89中导致未定义的行为.
Note: your program still causes undefined behaviour in C89 because the implicit declaration is int func();
but the function definition has void func()
which is incompatible type.
这篇关于为什么无需为外部函数添加`extern`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!