0

I have to call a static functions inside a class(say UserApp) which returns static value. Class Definition and declaration done in 2 files.

File1.h:

userApp(){

    static int* foo;
}

file1.cpp:

{
    int* userApp::foo = 0;
    ...
    .
    .

    foo = somevar;

}

The same class(userApp) is implemented in file2 and to avoid linkage error I'm forced to declare and define the static variable in file2 as well.

In file 2.cpp as userApp::foo is initialized to 0 , the return value of function getFoo is always zero.

I need the value associated to foo in file1. Is there any way I can avoid defining static variable in file2? Thanks in advance.

Madhu
  • 61
  • 1
  • 9

2 Answers2

0

What a mess :D

If I understood you right, I believe you have to declare the static member as extern in one of the files, to indicate it's actually referencing to a variable declared elsewhere.

Kahler
  • 1,130
  • 6
  • 24
  • Two files has declaration and implementation of same class[with some variations in functionalities].Thus the static member variables and functions are to be defined in both r8? – Madhu Apr 03 '14 at 15:53
  • Aw, now wait... You are defining the same class in a different way in each file and including both files? – Kahler Apr 03 '14 at 16:02
  • That won't work because then it's impossible to tell to which foo you are referring. Give a different name to each class and decide when you want class1::foo or class2::foo. If you want them both to be the same, again, make two different classes and make one of them's foo refer to the other one's foo. – Kahler Apr 04 '14 at 18:56
  • If you define a class twice, when you call class::foo, how to know which implementation are you calling? – Kahler Apr 04 '14 at 18:58
0

In UserApp.h:

class UserApp {
private:
    static int* foo_;
public:
    static int* getFoo() { return foo_; }
};

In UserApp.cpp:

#include "UserApp.h"

int* UserApp::foo_ = NULL;

In any other where you need to use it:

#include "UserApp.h"
...
int* foo = UserApp::getFoo();

You haven't provided any details about your namespace / class full of static things, but consider making more OO design or in case it seems reasonable to keep it in one class, consider implementing a singleton that would also allow you to hold the information about its state in more reasonable way. (you might end up with something like this)

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167