Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a global static variable from another class

Tags:

c++

I am working with code that has a global static variable (which is an object) and I need access to it from another class. I have always avoided global variables/functions in general so in this situation I am not sure how to go about it properly.

Just to clear my understand of things, in a global static variable has internal linkage, which means that any source file that includes this particular header will get its own copy of the variable?

EDIT: What I have tried so far is making a function which returns the address of the variable. Unfortunately, that does not seem to be working.

// names were changed but the code is as follows. 
// There is of course other code in the header
namespace SomeNameSpace
{
    static anArray<someObject> variable;
}

NOTE: I cannot change the code in the header where the global static variable is declared. I can add functions but I should try to avoid it if I can.

like image 284
Samaursa Avatar asked Apr 04 '11 14:04

Samaursa


People also ask

How do I use a variable from another class in C++?

If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.

Can we access static variable from another class?

A static variable can be accessed inside any other class using the class name.

Can we access static global 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

When you declare in you header file

static int g_foo;

and include this header file in multiple .cpp files, you get multiple instances one for each .cpp file that includes the header. These instances does not interfere at all. You can't communicate between the compilation units with these variables. Each instance is local to the compilation unit.

When you declare

class Foo
{
    public:
        static int bar;
};

then you get one static member that must be defined in one .cpp file as int Foo::bar; The accessibility is defined as public in this case.

like image 95
harper Avatar answered Oct 05 '22 23:10

harper