A global static variable that does not "remain defined" outside the function
I have a program where a static variable that I have defined globally will not be initialized after it leaves my "initialization function" (not the constructor). This program is:
type.h
namespace type
{
static int * specialInt;
}
type.cpp
#include "type.h"
(this is intentionally left blank)
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;
}
Output signal
Address from initInt (): 007F5910
Address: 00000000
before the crash. I read that the keyword static
allows variables to be linked externally, so why doesn't that succeed? Why initInt()
does the variable become undefined outside ?
source to share
namespace type
{
static int * specialInt;
}
This is the definition of a static integer pointer. static
in the namespace scope asks for internal binding: each translation unit that includes type.h
gets its own independent version specialInt
. Then, of course, changes made to one specialInt
do not affect the others.
What you want to do is declare a variable in type.h
:
namespace type
{
extern int * specialInt;
}
... and provide one definition in one of the translation units:
#include "type.h"
int *type::specialInt;
This definition will be found and used by everyone through type.h
.
source to share
I read that the keyword
static
allows variables to have external binding,
No, when static is used with an object in namespace scope, it specifies an internal binding. This means that the specialInt
assigned to Branch.cpp
and specialInt
printed to Leaf.cpp
is not the same object.
3) ... When used in a namespace-scope declaration, it indicates an internal link.
source to share