简体   繁体   English

如果在函数内部使用extern声明怎么办?

[英]What if using extern declaration inside the function?

I've tried the following code and got an error. 我尝试了以下代码,但出现错误。

int main()
{
    //this will cause redefinition error
    extern int x;
    int x=2; 
}

I've seen some answers about extern such as 我已经看到了有关extern的一些答案,例如

When to use extern in C++ 何时在C ++中使用extern

Defining extern variable in main() vs. globally 在main()与全局中定义extern变量

and got an concept,but I am still wondering what does the compiler do in this case. 有了一个概念,但是我仍然想知道在这种情况下编译器会做什么。 Can extern be used(legal) inside some function? extern可以在某些函数内使用(合法)吗?

update: 更新:

More specifically, since extern int x is just a declaration,why can't I define int x? 更具体地说,由于extern int x只是一个声明,为什么不能定义int x? Does the compiler take extern int x as a definition? 编译器是否将extern int x作为定义?

Of course it can be used, don't define another x inside the function: 当然可以使用它,不要在函数内部定义另一个x

int main()
{
    extern int x;
    x=2; 
}

but I am still wondering what does the compiler do in this case. 但是我仍然想知道在这种情况下编译器会做什么。 Can extern be used(legal) inside some function? extern可以在某些函数内使用(合法)吗?

it can, but you must not redeclare variable as you have in your code. 可以,但是您不能像在代码中那样重新声明变量。 So this is a valid example: 因此,这是一个有效的示例:

int main()
{
    //this will cause redefinition error
    extern int x;
    x=2; 
}

int x; 

As the others have answered, yes, you can use it in your function as long as you don't declare another variable with that name. 正如其他人回答的那样,是的,只要不使用该名称声明另一个变量,就可以在函数中使用它。

To your question of what the compiler does, dreamlax's answer to the question you linked, handles it pretty well. 对于您的编译器功能问题,dreamlax对您链接的问题的回答非常好处理。 The compiler doesn't need to do/know anything other than what it's type is so that it knows how it can be used. 编译器不需要/不知道其类型是什么,因此知道如何使用它。 The linker will see that it's an extern and know that it needs to go find where it is actually declared. 链接器将看到它是一个外部变量,并且知道它需要去查找实际声明的位置。

This MSDN link provides more general info on externs and what Microsoft does in VS 2015. MSDN链接提供了有关externs以及Microsoft在VS 2015中所做的操作的更多常规信息。

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

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