How to pass a static variable between source files in C ++?

I donโ€™t know if this can be done, but I tried several ways and nothing works. Basically, I need to access the same static member from multiple files that 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 the class definition (another .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 expect the call to the second function to change the value of S :: foo to 1, but the result is all the same:

2

Is the Ah file a local copy of a static class?

Thank. Tommaso

+3
source share
1 answer

This line:

int S::foo = 0;

, . S.h S.cpp.

+12

Source: https://habr.com/ru/post/1741285/


All Articles