[英]Global static variable not “staying defined” outside of function
I have a program in which a static variable I defined globally will not remain initialized once it leaves my "initialization function" (not a constructor). 我有一个程序,其中我全局定义的静态变量一旦离开我的“初始化函数”(不是构造函数)就不会保持初始化状态。 Here is that program:
这是该计划:
type.h type.h
namespace type
{
static int * specialInt;
}
type.cpp type.cpp
#include "type.h"
(this is intentionally left empty) (故意留空)
Branch.h Branch.h
#include "type.h"
namespace type
{
bool initInt();
}
Branch.cpp Branch.cpp
#include "Branch.h"
#include <iostream>
namespace type
{
bool initInt()
{
specialInt = new int;
*specialInt = 95;
std::cout << "Address from initInt(): " << specialInt << std::endl;
return true;
}
}
Leaf.h Leaf.h
#include "Branch.h"
#include <iostream>
namespace type
{
void PrintInt();
}
Leaf.cpp Leaf.cpp
#include "Leaf.h"
namespace type
{
void PrintInt()
{
std::cout << "Address: " << specialInt << std::endl;
std::cout << "Value: " << *specialInt << std::endl;
}
}
main.cpp main.cpp中
#include "Leaf.h"
int main()
{
type::initInt();
type::PrintInt();
return 0;
}
The output is 输出是
Address from initInt(): 007F5910
来自initInt()的地址:007F5910
Address: 00000000
地址:00000000
before it crashes. 在它崩溃之前。 I read that the keyword
static
lets variables have external linkage, so why is this failing? 我读到关键字
static
让变量有外部链接,为什么这会失败? Why does the variable become undefined outside of initInt()
? 为什么变量在
initInt()
之外变得不定义?
namespace type
{
static int * specialInt;
}
This is a definition of a static integer pointer. 这是静态整数指针的定义 。
static
at namespace scope requests internal linkage: every translation unit which includes type.h
gets its own, independent version of specialInt
. 命名空间范围内的
static
请求内部链接:包含type.h
每个翻译单元都有自己独立的specialInt
版本。 Then, of course, changes made to one of the specialInt
s do not affect the other ones. 然后,当然,对其中一个
specialInt
的更改不会影响其他的。
What you wan to do is declare the variable in type.h
: 你要做的是在
type.h
声明变量:
namespace type
{
extern int * specialInt;
}
... and provide a single definition in one of the translation units: ......并在其中一个翻译单元中提供单一定义:
#include "type.h"
int *type::specialInt;
This definition will then be found and used by everyone via type.h
. 然后,每个人都可以通过
type.h
找到并使用该定义。
I read that the keyword
static
lets variables have external linkage,我读到关键字
static
让变量有外部链接,
No, when static is used with object at namespace scope, it specifies internal linkage. 不,当static与命名空间范围内的对象一起使用时,它指定内部链接。 That means, the
specialInt
assigned in Branch.cpp
, and the specialInt
printed in Leaf.cpp
, are not the same object. 这意味着,
specialInt
分配的Branch.cpp
和specialInt
打印的Leaf.cpp
不是同一个对象。
3) ... When used in a declaration at namespace scope, it specifies internal linkage.
3)...当在命名空间范围内的声明中使用时,它指定内部链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.