开发者

pass static variable between two files in C/C++

开发者 https://www.devze.com 2023-01-18 07:16 出处:网络
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

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, 开发者_如何学JAVAwhat should I do?


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.


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


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...


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消