简体   繁体   English

extern short i有什么问题? i = 2; ? gcc抱怨类型冲突

[英]What is wrong with extern short i; i=2; ? gcc complains type conflict

The following code is similar to that of question Is there a difference between initializing a variable and assigning it a value immediately after declaration? 以下代码与问题类似: 初始化变量和在声明后立即为其赋值之间是否有区别? downvoted twice, so I am at risk ;-) 两次否决票,所以我处于危险之中;-)

short i; 
i = 2;

It does not compile with MinGW and -std=c99 -- why? 它不能与MinGW和-std = c99一起编译-为什么? The first line is a declaration of identifier i, not a definition of an object. 第一行是标识符i的声明,而不是对象的定义。 However, the identifier has file scope and thus external linkage by default. 但是,标识符具有文件范围,因此默认情况下具有外部链接。 It may be declared and defined elsewhere. 它可以在其他地方声明和定义。 The second line could be an assignment to that object. 第二行可以是对该对象的分配。 But gcc complains about a missing type or storage class and --after guessing the type as int-- about a type conflict. 但是gcc抱怨缺少类型或存储类,并且在猜测类型为int之后抱怨类型冲突。

You say that short i; 你说short i;short i; has file scope, which implies to me that it ( edit: and the subsequent i = 2; ) is outside a function. 具有文件范围,这对我来说意味着它( 编辑:和随后的i = 2; )在函数之外。 Outside a function, i = 2; 在函数之外, i = 2; on its own is complete nonsense; 完全是胡说八道; as a statement, it cannot appear outside a function. 作为声明,它不能出现在函数外部。 (edit) As statements cannot appear outside functions, the "assignment" must be a definition. (编辑)由于语句不能出现在函数外部,因此“赋值”必须是定义。 In old C code, a definition without a storage class was an int definition, so your code is equivalent (under those rules, which it looks like GCC is applying) to: 在旧的C代码中,没有存储类的定义是一个int定义,因此您的代码(在这些规则下,看起来就像GCC正在应用)等效于:

short i;
int i = 2;

which of course is complete nonsense to a C compiler. 当然,对于C编译器而言,这完全是胡说八道。 (end edit) (结束编辑)

You can get more-or-less the effect you're after by defining and initializing: 通过定义和初始化,您可以获得或多或少的效果:

short i = 2;

This does not work if you merely wish to declare an external variable; 如果仅希望声明一个外部变量,则此方法不起作用。 in that case, put the initialization in the file with the definition, or in one of your functions (as below). 在这种情况下,请将初始化放在带有定义的文件中,或者放在您的函数之一中(如下所示)。

extern short i;
int main(int argc, char **argv) { i = 2; /* more code */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM