static member variables across files...

R

Rahul

Hi Everyone,

I have a class having a static member variable in a header file.

File.h

class india
{
public:
static int a;
};

File1.cpp

#include "file.h"
int india::a = 5;

Now i want to access the same static member variable in another file
File2.cpp, what is the best possible way to do so?

Thanks in advance ! ! !
 
M

Marcel Müller

Rahul said:
#include "file.h"
int india::a = 5;

Now i want to access the same static member variable in another file
File2.cpp, what is the best possible way to do so?


#include "file.h"

void foo()
{ ++india::a;
}
 
P

programmer

Would the static variable india::a be initialized for sure by the
time, linker is working on file2.o?

I think it works, you can access the india::a in the file2.cpp when
the file1.cpp is in your project or makefile.If you do not include the
file1.cpp in your makefile, the class will not be implemented, the
linker will not work properly. So you must include the implemented
file in your makefile and the india::a will be initialized once.
 
N

nurxb01

I think it works, you can access the india::a in the file2.cpp when
the file1.cpp is in your project or makefile.If you do not include the
file1.cpp in your makefile, the class will not be implemented, the
linker will not work properly. So you must include the implemented
file in your makefile and the india::a will be initialized once.

Static members are only gauranteed to be initiallized before call to
main() happen.
But if there has been a call made to function foo() while constructing
a global static or global object, there are good chances that the
function call will give wrong results.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top