在什么情况下可以使用extern变量定义? [英] Under what circumstances can an extern variable be used in definition?
问题描述
我很抱歉。我不知道我不完整的代码附件会创建这样的混乱。我很高兴看到这么多真诚的帮助。
I am very very sorry. I didn't know my incomplete code attachment would create such a mess. I am very glad to see so many sincere helps.
此代码将编译:
int myadd(int, int);
static int main_stat = 5;
int main()
{
int i, j;
main_stat = 13;
j = myadd(-1,7);
i = main_stat;
cout << j << i; // 3 and 13
return 0;
}
myadd.cpp
myadd.cpp
extern int main_stat = -3;
int myadd(int x,int y)
{
int t = main_stat;
t = x + y;
y = t +main_stat;
return y; // will return 3
}
请参阅我定义和外部链接main_stat。为什么是合法的?我以为你只能链接和不定义。
See I defined and extern linking main_stat. Why is that legal? I thought you could only link and not define.
存储是否分配在myadd函数调用的堆栈帧中?全局静态是在堆上分配的,我相信是对吗?
Is storage allocated in the stack frame of myadd function call? Global static are allocated on heap, I believe, right?
对不起,我想这次我会缩小我的问题:
I am sorry, but I think this time I will narrow down my questions:
来自C ++ Primer 4ed
From C++ Primer 4ed
extern 声明可能包含一个初始化程序(当组合
时变为定义),只要它出现在函数之外。
An extern declaration may include an initializer (when combined becomes definition) only if it appears outside a function.
我清楚单一定义规则。
I am clear about one-definition rule.
Q1。 myadd(int,int)在调用main_stat时使用哪个副本?与main相同的副本,但具有不同的值(我可以测试)?或者每个函数都有自己的静态全局副本?
Q1. Which copy of main_stat does myadd(int,int) uses when it is called? The same copy as the main has, but with a different value (which I can test) ? Or does each function has its own static global copy?
Q2。在堆上为这些全局静态变量分配内存吗?我知道很多事情是由实现,但不是堆用于静态变量?
Q2. Is memory allocated on the heap for these global static variables? I know many things are up to implementation, but isn't heap used for static variables?
Q3。我知道以下两个是有效的
Q3. I know the followings two are valid
extern int x; // means int x is defined elsewhere
extern int x = 3; // declared and defined
为什么我们想要第二个,如果我们可以声明一个静态全局变量在myadd的命名空间内? 像aschepler说的那样?
Why do we want the second one if we can just declare a static global variable within the namespace of myadd ? How does it make things clear like aschepler said?
推荐答案
使用初始化程序的所有变量声明也是定义;
这是一个重要的规则。无论 extern
。还有
的情况下,你需要一个 extern
定义:你只能
使用具有外部链接的变量实例化模板。和
const
默认情况下具有内部链接,所以你需要
类似:
All variable declarations with an initializer are also definitions;
that's an overriding rule. Regardless of extern
. There are even
cases where you need an extern
on a definition: you can only
instantiate a template using a variable which has external linkage. And
const
variables have internal linkage by default, so you need
something like:
extern int const i = 42;
如果你想使用它来实例化一个模板< int const *> ;
。
if you want to use it to instantiate a template<int const*>
.
这篇关于在什么情况下可以使用extern变量定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!