什么是落后于C / C采用的extern一个概念++? [英] What is a concept behind using extern in c/c++?

查看:162
本文介绍了什么是落后于C / C采用的extern一个概念++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这类问题。但是,我对在ç\\ C ++关键字的extern 很好奇

同时寻找解释的extern 我知道,的extern 告诉编译器变量或函数在一些其他的文件或程序已经定义

但如果是这种情况,那么为什么我们使用的extern

因为我尝​​试了一些codeS如下:

 的extern INT无功;
INT主要(无效)
{
 变种= 10;
 返回0;
}

这code是给我的错误消息为解析的外部符号INT VAR(?VAR @@ 3HA)

如果我使用了一些code,如:

 的extern INT无功;
INT主要(无效)
{
 INT变种= 10;
 返回0;
}

它不显示任何错误,并给出了相同的价值正如我在主函数中定义。

所以,任何一个可以帮我约的extern 的行为?
我对这个有点困惑。
请原谅我,如果它不是一个有效的问题。
谢谢你在前进。


解决方案

的extern 用于引用变量的另一个翻译单位(源文件)


例如,在你的main.c code是这样的:

 的extern INT无功;
INT主要(无效)
{
    变种= 10;
    返回0;
}

这code包含一个整数名为VAR的声明,但没有定义,因为EXTERN明确表示:这样做的定义是在别处

您可以定义另一个源文件,说,other.c:

  INT VAR = 0;

然后,这个新的翻译单元添加到您的构建命令后,你的程序将链接罚款,并在这两个文件中的code可以在共享 VAR操作变量。

在第二个版本,你只覆盖的extern VAR 的声明与主函数中的局部变量。由于采用了将extern VAR 不是(ODR-),链接器并不需要它,所以你的可执行文件可以成功打造。

Sorry for this type of question. But, I am very curious about the keyword extern in C\C++.

while searching for explanation for extern I got to know that extern tell the compiler that the variable or function is already defined in some other file or program.

But if this is a case then why we use extern?

as I tried some codes as follows:

extern int var;
int main(void)
{
 var = 10;
 return 0;
}

This code is giving me an error message as unresolved external symbol "int var" (?var@@3HA).

and if I am using some code like:

extern int var;
int main(void)
{
 int var = 10;
 return 0;
}

It is not showing any error and gives value same as I have defined in main function.

So, Can any one help me about the behavior of extern? I am little confused on this. Please forgive me if it is not a valid question. Thank you in Advance.

解决方案

extern is used to refer to a variable in another translation unit ("source file"). For instance, your code in main.c looks like this:

extern int var;
int main(void)
{
    var = 10;
    return 0;
}

This code contains a declaration for an integer named var, but no definition, because extern explicitly says: "the definition for this is somewhere else"

You could define another source file, say, other.c:

int var = 0;

Then, after you add this new translation unit to your build command, your program will link fine, and the code in both files can operate on the shared var variable.

In the second version, you just override the declaration of the extern var with a local variable in your main function. Since the extern var is not (ODR-)used anymore, the linker does not require it, so your executable can build successfully.

这篇关于什么是落后于C / C采用的extern一个概念++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆