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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Aw, now wait... You are defining the same class in a different way in each file and including both files?
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.
If you define a class twice, when you call class::foo, how to know which implementation are you calling?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.