Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

static

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?

like image 358
skydoor Avatar asked Dec 17 '22 21:12

skydoor


1 Answers

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.

like image 200
CB Bailey Avatar answered Dec 27 '22 12:12

CB Bailey