static variable cpp do not want to change

c++, static-variables

Solution

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.

Problem

``` 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.

Original source