Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing static variables across files: namespace vs class

There are a lot of questions about static vs global here but I think my question is a bit different.

I want to know if there is a way to share a variable placed in a namespace across files the way static variables in a class can.

For example, I coded this:

//Foo.h
class Foo
{
  public:
  static int code;
  static int times_two(int in_);
};

namespace bar
{
  static int kode;
}

-

//Foo.cpp
int Foo::code = 0;

int Foo::times_two(int in_)
{
  bar::kode++;
  code++;
  return 2*in_;
}

-

//main.cpp
int main()
{
  cout << "Foo::code = " << Foo::code << endl;

  for(int i=2; i < 6; i++)
  {
    cout << "2 x " << i << " = " << Foo::times_two(i) << endl;
    cout << "Foo::code = " << Foo::code << endl;
    cout << "bar::kode = " << bar::kode << endl;

    if(i == 3)
    {
      bar::kode++;
    }
  }
}

All that yielded this for code and kode:

Foo::code = 1,2,3,4
bar::kode = 0,0,1,1

Once again, is there a way to share a variable placed in a namespace across files the way static variables in a class can? The reason I ask is because I thought I would be able to shield myself from confliciting global variables by using :: notation, and just found out I could not. And like any self-disrespecting programmer, I believe I am doing it wrong.

like image 957
Morpork Avatar asked May 10 '12 13:05

Morpork


People also ask

Are static variables shared between classes?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.

Are static variables shared by all objects of a class?

A static variable is shared by all instances of a class. Only one variable created for the class.

Are namespace variables static?

By default, an object or variable that is defined in the global namespace has static duration and external linkage. The static keyword can be used in the following situations.

Can we use static variable in another file?

Static variables in C have the following two properties: They cannot be accessed from any other file. Thus, prefixes “ extern ” and “ static ” cannot be used in the same declaration. They maintain their value throughout the execution of the program independently of the scope in which they are defined.


1 Answers

Yes:

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

Outside of a class or struct, static has a whole different meaning. It gives a symbol internal linkage. So if you declare the same variable as static, you will actually get a different copy for all translation units, not a unique global.

Note that you'll need to initialize the variable once:

//bar.cpp
namespace bar
{
   int kode = 1337;
}
like image 109
Luchian Grigore Avatar answered Nov 14 '22 01:11

Luchian Grigore