Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
Adrian Avatar asked Oct 31 '25 12:10

Adrian


2 Answers

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.

like image 197
Joseph Mansfield Avatar answered Nov 03 '25 03:11

Joseph Mansfield


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.

like image 32
Zyx 2000 Avatar answered Nov 03 '25 05:11

Zyx 2000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!