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
namespace type
{
static int * specialInt;
}
type.cpp
#include "type.h"
(this is intentionally left empty)
Branch.h
#include "type.h"
namespace type
{
bool initInt();
}
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
#include "Branch.h"
#include <iostream>
namespace type
{
void PrintInt();
}
Leaf.cpp
#include "Leaf.h"
namespace type
{
void PrintInt()
{
std::cout << "Address: " << specialInt << std::endl;
std::cout << "Value: " << *specialInt << std::endl;
}
}
main.cpp
#include "Leaf.h"
int main()
{
type::initInt();
type::PrintInt();
return 0;
}
The output is
Address from initInt(): 007F5910
Address: 00000000
before it crashes. I read that the keyword static
lets variables have external linkage, so why is this failing? Why does the variable become undefined outside of 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
. Then, of course, changes made to one of the specialInt
s do not affect the other ones.
What you wan to do is declare the variable in 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
.
I read that the keyword static
lets variables have external linkage,
No, when static is used with object at namespace scope, it specifies internal linkage. That means, the specialInt
assigned in Branch.cpp
, and the specialInt
printed in Leaf.cpp
, are not the same object.
3) ... When used in a declaration at namespace scope, it specifies internal linkage.
链接地址: http://www.djcxy.com/p/35332.html上一篇: 如何验证Moq中没有调用该方法?
下一篇: 全局静态变量不在函数外部“保持定义”