tags:

views:

78

answers:

5

Hi, I have a question to ask about passing static variables between two files.

Now I have one file A.c and a second file B.cpp

In A.c

static struct {
   int 
   int 
} static_variable

Now A.c has to call a function func() in B.cpp, and this function has to modify the static_variable in A.c

In B.cpp

func() {

  static_variable = ***;

}

I understand that B.cpp can't access the static variable in A.c, so if I really need to do so, what should I do?

A: 

Firstly, your struct is invalid because you don't specify names for the types.

Second, you have not declared anything static...

Finally, I'm not really sure what you're trying to do... You can certainly pass structs to functions, in a number of different ways...

dicroce
+7  A: 

The whole point of static is to give a object or function internal linkage so you can't refer to it from outside the translation unit. If this isn't the behaviour that you want then you should not make it static. You can define it in one translation unit and declare it extern in the other.

Even if the variable is static you could pass a pointer to the static variable to the function in the other translation unit. The internal linkage only applies to the name of the variable, you can still access it by means that don't require you to name the variable.

Charles Bailey
A: 

The static qualifier means that the name is not available to the linker, so you cannot directly access the variable via its name from a different file, but there are other ways to access a variable.

You need to do two things:

  1. ensure that the declaration of the struct in question is available to B.cpp (i.e. put the declaration in a header file included by both)
  2. Pass a pointer (or in c++, a reference) to the variable to func. This can either be directly as an argument, or (uglier!) via a non-static variable.
jsegal
+1  A: 

I would define a getter and a setter function in A.c. The prototypes can be put in A.h.

Then B.c would include A.h and call the setter instead of setting the variable directly.

Using a setter/getter has a bunch of advantages:

  • Handling of concurrent access possible
  • Central point for logging changes to the variable
jdehaan
A: 

Solution 1: Put func() in A.c. This is where it should belong. (EDIT [thanks to Ben Voigt]: But you may not do this if func() uses C++ features).

Solution 2: Write get_static_variable() and set_static_variable() functions in A.c and call them from B.c.

Note: I assumed that the code you provided contains typo and I followed your description.

Donotalo
Solution 1 may not be possible if `func()` uses C++ features (it is in a .cpp file now after all).
Ben Voigt
hmm, you're right. didn't notice it is in cpp file.
Donotalo