Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a static variable between C++ source files?

I don't know if it is possible to do this, but I have tried several ways and nothing seems to work. Basically I need to access the same static member from several files which include the same class definition.

// Filename: S.h

class S {
public:
    static int foo;

    static void change(int new_foo) {
        foo = new_foo;
    }

};

int S::foo = 0;

Then in a class definition (other .cpp file) I have:

// Filename: A.h

#include "S.h"    

class A {
public:
    void do_something() {
        S::change(1);
    }
};

And in another file:

// Filename: program.cpp

#include "S.h"
#include "A.h"

int main (int argc, char * const argv[]) {
    A a = new A();
    S::change(2);        

    std::cout << S::foo << std::endl;

    a->do_something();

    std::cout << S::foo << std::endl;

}

Now, I would expect the second function call to change the S::foo to 1, but the output is still:

2

Is the A.h file creating a local copy of the static class?

Thank you Tommaso

like image 239
tunnuz Avatar asked Dec 13 '22 22:12

tunnuz


1 Answers

This line:

int S::foo = 0;

needs to be in exactly one source file, not in the header. So move it from S.h to S.cpp.

like image 77
interjay Avatar answered Dec 15 '22 14:12

interjay