Question

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.

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top