Pass a static variable between two files in C / C ++

I have a question to ask about transferring static variables between two files.

Now I have one Ac file and a second B.cpp file

In ac

static struct { int int } static_variable 

Now Ac should call the func() function in B.cpp, and this function should change the static_variable in Ac

In B.cpp

 func() { static_variable = ***; } 

I understand that B.cpp cannot access the static variable in Ac, so if I really need to do this, what should I do?

+4
source share
5 answers

The whole point of static is to give an internal connection to an object or function so that you cannot refer to it from outside the translation unit. If this is not the behavior you want, you should not be static. You can define it in one translation module and declare it extern in another.

Even if the variable is static , you can pass a pointer to the static variable in a function in another translation unit. Intercom only applies to the name of the variable, you can still access it without requiring you to specify this variable.

+11
source

I would define the getter and setter function in Ac. Prototypes can be placed in Ah

Then Bc will turn on Ah and call setter instead of setting the variable directly.

Using setter / getter has several advantages:

  • Simultaneous access
  • Center point for recording changes to a variable
+1
source

First, your structure is not valid because you are not specifying names for types.

Secondly, you did not declare anything static ...

Finally, I'm not quite sure what you are trying to do ... Of course, you can pass structures to functions in different ways ...

0
source

A static determinant means that the name is not accessible to the linker, so you cannot directly access the variable through your name from another file, but there are other ways to access the variable.

You need to do two things:

  • make sure the declaration of the structure in question is available for B.cpp (i.e. put the declaration in the header file included by both)
  • Pass a pointer (or in C ++, a link) to a variable in func. This can be either directly, or an argument, or (ugly!) Using a non-static variable.
0
source

Solution 1: Put func() in Ac Here it should be. (EDIT [thanks Ben Voigt]: But you cannot do this if func() uses C ++ functions).

Solution 2: Write the functions get_static_variable() and set_static_variable() in Ac and call them from Bc

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

0
source

All Articles