Static Global Variable Not Shared Between Threads [duplicate] - c++

I know that this program is not using the static variable in an appropriate way, but it shows how to reproduce a behavior I have seen :
Main.cpp :
int main(){
MyObject* p = new MyObject();
Header::i = 5;
printf("i %i\n", Header::i);
p->update();
return 0;
}
MyObject.cpp :
MyObject::MyObject(){
}
void MyObject::update(){
printf("i %i\n", Header::i);
}
Extern.h :
namespace Header {
static int i;
};
The output I get is :
i : 5
i : 0
Why don't I get 5 for both outputs ? Where does this 0come from ?
Could you explain how static variables work ?

Static variables have internal linkage which effectively means they are local to the compilation unit. Since you have the static variable declared in a header included in 2 source files, you basically have 2 distinct variables: one i local to MyObject.cpp and another, different i, local to main.cpp

You have one static variable per translation unit where you include the header, because static variables have internal linkage.
Where does this 0 come from ?
You've not initialized the variable in the second translation unit, and static variables are zero-initialized, that's where the 0 comes from.
In the standard (§3.6.2/2):
Variables with static storage duration (3.7.1) [...] shall be zero-initialized (8.5) before any other initialization takes place.[...]

You have two variables i
static int i;
because it has internal linkage. That means that each compilation unit where the corresponding header was included has its own object i and other compilation units know nothing about presnece of that object in this compilation unit.
If you will remove specifier static then the linker should issue a message that the variable is defined twice.
The same effect can be achieved if to place a variable in an unnamed namespace in C++ 2011. For example instead of
namespace Header {
static int i;
};
you could write
namespace {
int i;
};
In this case varaible i also has internal linkage. This is valid for C++ 2011.

You should not put static valiables in header files. That leads to every cpp file that includes that header to have a copy of that static local to its compilation unit.
What you could do is extern storage specifier:
Header:
namespace Header {
extern int i;
}
Cpp:
namespace Header {
int i = 0;
}

As an addition to the all the answers. WHY it happens, was already explained. However HOW to fix it, was suggested till now only by using static/extern approach. This is little bit C-like. Unles you don't have to use the header in C-part of the project with C-linkage, you could use C++.
So IF you have really to use something static in your code.
Either declare the variable as a member of a class:
header.h
MyGlobalVariableHoler
{
public: static int i;
};
main.cpp
// class' statics have has to be initialized, otherwise linker error.
int MyGlobalVariableHoler::i=0;
any_code.cpp
#include <header.h>
MyGlobalVariableHolder::i=4711;
Or use a singleton to avoid the explicit initialization
header.h
MyGlobalVariableHolder
{
MyGlobalVariableHolder(){i=0;}
public:
static MyGlobalVariableHolder & instance()
{
static MyGlobalVariableHolder inst;
return inst;
}
int i;
};
any_code.cpp
#include <header.h>
MyGlobalVariableHolder::instance().i=4711;

Its better to declare your variable with extern in your header file to specify that it has an external linkage. Otherwise the above behavior will occur or potential compile or link problems can happen.
static int i ; // i has internal linkage
extern int i ; // i has external linkage

You are getting confused with class level static variable with namespace level static variable. Both are accessed by X::y qualification, adding to confusion. Others have explained actual reason (at the compilation/linkage level).

The variable that is declared static only has scope in the file in which it is declared where as the variable declared without static can be accessed from other files using an extern declaration.

Related

Correct way of initializing a class globally in C++

I know global is bad but just as a practice, is this the correct way to initialize a global class used between multiple object files?
Header 1.h
class test {
int id;
public:
test(int in){
id = in;
}
int getId(){
return id;
}
};
extern test t;
File 1.cc:
#include <iostream>
#include "1.h"
int main(){
std::cout << t.getId() << std::endl;
return 0;
}
File 2.cc:
#include "1.h"
test t(5);
Now what if instead of extern I use the static approach globally static test t(0); in the header?
Correct me if I'm wrong but that would compile fine however I would have 2 different unrelated copies of the same t in both object files and the final binary? Is that bad? Or does the linker sort it out to eliminate multiple copies?
There are global instances, not global classes.
What you have is a global instance. And yes, this sounds about right, until you get to multiple global instances which depend upon each other. Then the real fun will start.
Defining a variable as 'static' at global level means the variable will be defined in the compilation unit only (i.e. the '.o' file) and the symbol won't be exported by the compiler.
In other words: yes, there will be multiple variables with the same name but only visible to functions on the same compilation unit.
Besides, 'invisible' doesn't mean 'inaccessible'. You still can provide access to the variable. For example:
1.h
struct Test { int value; }; // Class definition
Test& get_t(); // Function declaration
1.cc
#include "1.h"
static Test t; // Variable declared as 'static'
Test& get_t() { return t; };
2.cc
#include "1.h"
#include <iostream>
int main()
{
std::cout << get_t().value << std::endl; // Static variable accessed
}
I use the static approach globally static test t;?
But your test class needs an int in parameter for the constructor, so you want:
static test t(0); // or whatever int you want
If you turn the extern to static in the header, you would define a static variable in each compilation unit in which the header is imported. So classes in different cpp files would no longer "communicate" via t, since each would have theirs. This is very error prone.
In addition, adding the definition of a static in a header is an extremely bad practice. When someone includes a header, one does not expect that it will create variables.
Including the declaration of t as extern is an acceptable practice. But be aware that if the header has a general purpose, this might reduce its reusability other projects.
More information of interest for you:
Must read: C++ Core Guidelines about source files
Must read: Guidelines for writing headers
StackOverflow: When are global variables recommended
Why global variables should be avoided if possible and when are they ok
If you put a variable declaration outside of any function, you're declaring the variable as 'global'. Ex:
1.cc
int this_is_global;
From here on you can use the variable in any function of '1.cc'.
For using the same variable in any other file, the compiler will need to know about it:
2.cc
extern int this_is_global;
Here, the keyword extern tells the compiler that the variable is declare somewhere else, letting the task of finding it to the linker.
If you miss to add the extern keyword here, the compiler will treat it as a new variable, and the linker will have two variables with the same name and will emit an error. All of your source files of your project except the first one will need the extern keyword to avoid duplicate symbols.
So common practice is to add the 'extern' declaration in an include file:
1.cc
int this_is_global;
1.h
extern int this_is_global;
2.cc
#include "1.h"
On the other side, the static keyword tells the compiler not to export the symbol. In other words: the variable will exists only in the source file it is declared. You could declare it once per source file and there will be different variables with the same name. Ex:
1.h
static int my_var;
1.cc
#include "1.h"
2.cc
#include "1.h"
This way, you'll end having two variables 'my_var' and changes to any of them won't affect the other.

extern variable and array declare issue c++

I have a problem with an extern variable and an array declaration with it.
How to declare an array with global variable which located not in the declarable file.
file1.cpp
const int size = 10;
mainfile.cpp
extern const int size;
void main()
{
int mas[size];
}
int mas[size];
This line has an issue.
Please any guess??
You can't. An array size must be a constant expression; if it's a variable, then that variable must be const and initialised in the same translation unit, so that its value is available for use as a constant.
If you want to share the value between multiple translation units, define it in a header and include that.
First of all constants have internal linkage. Thus these declarations
file1.cpp
const int size = 10;
and
mainfile.cpp
extern const int size;
refer to different entities.
The constant declared in file1.cpp is not visible outside its corresponding compilation unit.
According to the C++ Standard (3.5 Program and linkage)
3 A name having namespace scope (3.3.6) has internal linkage if it is
the name of
— a non-volatile variable that is explicitly declared const or
constexpr and neither explicitly declared extern nor previously
declared to have external linkage; or
In mainfile the value of size is not specified so the compiler will issue an error for statement
int mas[size];
becuase the size of an array shall be a compile-time constant expression.
The simplest solution is to place the constant definition
const int size = 10;
in some common headet file that will be included in each translation unit where there is a reference to the constant.
int mas[size];
This line has an issue. Please any guess??
As other users pointed, the issue could be that you're trying to create a Variable Lenght Array which is something not allowed in C++ (but almost enter in C++14 as Dynamic Arrays*).
Some compilers accept VLA as an extension (no standard) so I'm guessing that you're using one that doesn't have this extension or have this extension disabled.
Don't worry, you have workarrounds anyway...
#define (don't do that)
Assuming that the issue is the VLA, if we ensure the size as a compile-time value, the problem is solved so...
// file1.hpp <-- This is now a HEADER not a CPP
#define SIZE 10
// mainfile.cpp
#include "file1.hpp"
void main()
{
int mas[SIZE]; // accepted, equivalent to int mas[10].
}
constexpr
C++11 introduced the constexpr* keyword which can be used to achieve your goal
// file1.hpp <-- This is now a HEADER not a CPP
constexpr int size() { return 10; }
// mainfile.cpp
#include "file1.hpp"
void main()
{
int mas[size()];
}
enum
Enumerations are compile-time constants, so you can use them this way:
// file1.hpp <-- This is now a HEADER not a CPP
enum constant { size = 10 };
// mainfile.cpp
#include "file1.hpp"
void main()
{
int mas[constant::size];
}
*If someone found a better link, please let me know.
C++ does not allow the size of arrays to be specified at runtime. In your example of course it is specified at link time, but that is no help to the compiler.
If you are using a C++14 compiler however, and on certain other compilers (such as gcc) you can do this, but it is less portable than allocating the memory dynamically, and lest convenient than a std::vector<>.
For reference: https://isocpp.org/wiki/faq/freestore-mgmt#dynamic-array-len

static variable cpp do not want to change

FileA.hpp:
static int a;
void change(int);
FileA.cpp
#include "FileA.hpp"
void change(int x) { a = x; }
main.cpp
#include "FileA.hpp"
#include <cstdlib>
#include <iostream>
int main()
{
a = 5;
std::cout<<a<<std::endl;
change(10);
std::cout<<a<<std::endl;
a = 20;
std::cout<<a<<std::endl;
system("Pause");
return 0;
}
My output is:
5
5
20
Can someone help me with this? Why variable 'a' don't want to change in function
which is in FileA.cpp.
How to fix this. When I make change(int x) inline in "FileA.hpp" it works fine.
The static keyword on a global variable gives that variable internal linkage. It means that any translation unit that has that definition will have its own copy of the object. So the a object that main.cpp sees and that FileA.cpp sees are different objects. change will modify one of them, but main will output the other.
If you were intending static to mean that the object has static storage duration, global variables (or variables at namespace scope in general) have static storage duration anyway. You don't need to mark them static. However, if you remove static, you'll have another problem; you'll have multiple definitions of a across translation units.
The correct way to do this is to declare a as extern in the FileA.hpp file:
extern int a;
Then in a single translation unit (probably in FileA.cpp, define the object:
int a;
This means that any object that includes FileA.hpp will have the declaration of a (which is fine) and only one translation unit will have the definition of a. Perfect.
You declare a in the header file, which when included creates two copies of it, one in main.cpp and one in FileA.cpp. When you do a = 5; you assign to the copy from main.cpp, while when calling the function change, it changes the copy in FileA.cpp.

Not able to understand static behaviour

I wrote in
// In file t.h
#ifndef __t_h__
#define __t_h__
static int abc;
#endif
--
//In main.c
#include <stdio.h>
#include "t.h"
int main()
{
abc++;printf("%d \n", abc);
test();
}
- -
//In test.c
#include <stdio.h>
#include "t.h"
void test()
{
abc++;
printf("%d \n", abc);
}
When I run the project I found the output of abc is 1 and 1.
But when I change it to int abc in t.h. The output of abc = 1 and 2.
Why static is not retaining the value when the control reaches to test.c file.
If it won't retain then why should not it provide an error as the static variable can not be shared between/among the files?
static variables has internal linkage which means each translation unit gets its own copy.
So in your program each .cpp file which includes t.h has its own copy of the static variable, which in turn means, there are two objects in the memory. You can try printing their addresses to confirm this, as they will be different.
That makes the situation pretty simple: if you change the object in one .cpp, it doesn't reflect in the other .cpp file, because the object in the other .cpp file is a different object. Why should it change?
But when you change it to int abc (i.e don't make it static), then each translation unit has same object. If you change it in one file, it will be reflected in other file also, as expected.
As for sharing, then yes, static objects can be shared between two functions in the same translation unit, but they cannot be shared between two translation units.
Search for translation unit on this site, you will get many topics on it. Read them, then you will understand it fully.
When the preprocessor is done with your code, main.c looks like
// omitted stuff from stdio
static int abc;
int main()
{
abc++;printf("%d \n", abc);
test();
}
and test.c looks like
// omitted stuff from stdio
static int abc;
void test()
{
abc++;
printf("%d \n", abc);
}
So each file contains its own variable abc that is not accessible from the other.
One solution would be to change t.h to
#ifndef __t_h__
#define __t_h__
extern int abc;
#endif
and then change main.c to
#include <stdio.h>
#include "t.h"
int abc;
int main()
{
abc++;printf("%d \n", abc);
test();
}
You can think about it like this: there's now only one int abc in your program, in main.c but test.c knows about its existence because the extern int abc tells test.c that somewhere else in the project there is an integer called abc that it will be able to find at link time.
When you declare a static variable in header file a copy of the static variable is created in each Translation unit where the header is included. So each of the translation units involved in your program has its own copy of abc now and hence you get the observed behavior.The behavior is not what you expected but it well defined one.
static variable can not be shared between/among the files?
No they cannot be! that is the very purpose of making them static
static variables have internal linkage. Their scope is restricted to the the translation unit in which they are declared. They cannot be accessed beyond the TU.If you want to share the same variable across different Translation units You should drop the static and use extern, which gives the variable an external linkage and hence visibility across different translation units.
Good Read:
How do I use extern to share variables between source files?
In C, static has two usages:
1, Use static keyword to limit the var's scope in the translation unit. To make this simple, if you have two files: a.c, b.c and you wrote:
static int varA;
in a.c, then this means varA could only be used in a.c, if you want to use varA in b.c, you should remove the static keyword, and add extern int varA; in b.c, what people usually do is we create another file called: a.h, and write extern int varA; in a.h, and we simply include "a.h" in b.c, so we could write every variable we want to extern in a.h and use a single include "a.h" to make these variables or functions legal in other .c files(i.e. source files)
2, Using static to define a local variable in a function, for instance:
int TheFunction()
{
static int var = 0;
return ++var;
}
Because you used the static keyword on a local variable var, this variable will not loss when TheFunction() is returned.
The first time you call TheFunction() you will get 1, the second time you call TheFunction() you will get 2, and so on.
Next, lets see the usage of static in C++.
Because any C++ complier can complie a C code, so the 2 usages above is also in C++.
another two usages is:
1, static member variable.
2, static member function.
Lets see the code directly:
#include <iostream>
using namespace std;
class Test
{
public:
Test() : m_nNormalVar(0)
{
}
public:
// You need to init this static var outside the class
// using the scope operator:
// int Test::m_nStaticVar = 0;
static int m_nStaticVar;
// You can init this const static var in the class.
const static int m_nConstStaticVar = 10;
// This is just a normal member var
int m_nNormalVar;
};
int Test::m_nStaticVar = 0;
int main(int argc, char *argv[])
{
Test a;
Test b;
a.m_nStaticVar++;
a.m_nNormalVar++;
cout << b.m_nStaticVar << endl;
cout << b.m_nNormalVar << endl;
return 0;
}
a and b are objects of class Test they have the same m_nStaticVar and the same m_nConstStaticVar, but they have their own m_nNormalVar this is a static member variable.
#include <iostream>
using namespace std;
class Utility
{
public:
// This is a static member function, you don't
// need to have a concrete object of this class
// to call this function.
static int SelectMax(int a, int b)
{
return a > b ? a : b;
}
};
int main(int argc, char *argv[])
{
// No objects of class Utility
cout << Utility::SelectMax(2, 1) << endl;
return 0;
}
So this is a static member function of a class in C++.
These four ways of static's usage is all I known, if there are still some other usages, please help to edit this post, thx:)
EDIT:
Add static global function
1, Use static keyword to limit the function's scope in the translation unit. To make this simple, if you have two files: a.c, b.c and you wrote:
static void StaticFunction();
in a.c, so you can only call StaticFunction() in a.c, if you want to call this function in b.c you should remove the static keyword and then delcare it before the usage. Or just declare it in a.h and include "a.h" in b.c

How to access global const variable present in one file to different file

This variable is defined in xyz.cpp
const int i = 10;
The below main() method is written in abc.cpp
void main()
{
cout<<i; //trying to access 'i' from a different .cpp file
}
You need to declare it extern in abc.cpp:
extern const int i;
EDIT: As stated in the comment below, in C++ (unlike C), to give a const variable external linkage, you need to declare it es extern also in xyz.cpp:
extern const int i = 10;
Reference: MSDN
The simplest way is to declare it in a header as const static int i=10; and include that header in all the .cpp that need that constant. This will allow it to be "inlined" by the compiler in every object file, still avoiding ODR violations.
---edit---
Actually, in C++ the static is not required, since const objects have internal linkage by default. But in C, you have to put that static (and in C++ it doesn't hurt).
Why is this better than the extern method? Because:
it's more idiomatic. In C++ you'll always write integral constants in headers as const variables (and that's the very reason why they have internal linkage by default).
it's less typing. You just have to write the const declaration once, then your constants are just a #include away.
it (usually) produces more efficient code. The definition of extern-declared variables cannot be accessed by the compiler when it is producing the current object module, so it cannot optimize it by putting its actual value as an immediate value in the produced machine code, it cannot eliminate branches that cannot be reached with that value of the constant, ... Sure, cross-module optimization ("link time code generation", "whole program optimization", ...) does exist, but at the moment compilers have more advanced optimizers than linkers.
Add the keyword extern in front of it.
Declare it in abc.cpp as:
extern const int i = 10;
const variables in C++ have an internal linkage in C++(unlike C). So to be able to use it in another file you have to explicitly declare it as having external linkage.
Put this global variable into header and #include this header in all .cpp files where you want to use it.
xyz.h:
const int i = 10;
xyz.cpp:
#include "xyz.h"
void main()
{
cout << i;
}
Or if you want to avoid using header for this purpose, you can declare it as extern const int i = 10; in xyz.cpp, but then you have to declare this variable in abc.cpp too, so you should write extern const int i; at the beginning of abc.cpp in order to use it.
The same way as using extern variables.
In the file xyz.cpp:
extern const int i = 333;
In the file abc.cpp:
extern const int i;
cout << i;