Search code examples
c++namespacesextern

change namespace variable value from outside (C++)


consider the following namespace:

// foo.h
namespace foo
{
    extern int bar;
}

//foo.cpp
namespace foo
{
    extern int bar = 42;
}

is there a way to change the value of bar somewhere else in the project (i.e, not inside the namespace)?

I mean something like:

// in some other .cpp file
#include foo.h

int setBar(int x)
{
    foo::bar = x;
}

Solution

  • is there a way to change the value of bar somewhere else in the project (i.e, not inside the namespace)?

    Yes, almost exactly as you've shown. The only issue in your sample code is that you used extern in your foo.cpp file where you define your foo::bar variable. You need to remove extern from foo.cpp:

    #include <iostream>
    
    // foo.h
    namespace foo
    {
        extern int bar; // use extern in header file to declare a variable
    }
    
    // foo.cpp
    namespace foo
    {
        int bar = 42; // no extern in cpp file.
    }
    
    int setBar(int x)
    {
        std::cout << "old foo::bar: " << foo::bar << std::endl;
        foo::bar = x;
        std::cout << "new foo::bar: " << foo::bar << std::endl;
    }
    
    int main()
    {
        setBar(999);
    }
    

    Output:

    old foo::bar: 42
    new foo::bar: 999