Basically what I need is for two or more functions which reside in different source files and cannot know about each other to share some data. Globals would be an instant solution, but they're universally frowned upon. Could it be that they're pretty much inevitable in this case?
Here's a simplified explanation of what I need to do using globals:
file1.c
int foo;
void change_foo()
{
// Does some calculation to determine the new value of foo
foo = ...
}
file2.c
extern int foo;
void use_foo()
{
// Does something with the value of foo
// Is not aware of change_foo()'s existence so it can't call or be called from it
}
1) How would one eliminate the need for a global variable here? Making int foo static inside either function will instantly couple both functions. Defining the variable inside main() and then calling both functions from within main() is not an option for me.
2) Is there a more elegant solution in an OO language like C++? Say two methods from two different namespaces need to share data.
3) I can see this problem happening often. One noticeable example would be the need to share a resource or some other entity (that cannot be serializable in a meaningful way) between two independent android activities. Is there no way around using globals (a class with public static fields in this example) or a design pattern like singleton?
0 comments:
Post a Comment