Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share one static variable with multiple translation unit?

Tags:

c++

c

I want to make an array static and also want to reference it in the other translation unit. Then I define it as static int array[100] = {...}, and declare it in other translation unit as extern int array[]. But the compiler tells me that the storage class of static and extern conflict with each other, how could I pass it and still reach my goal?

like image 366
Thomson Avatar asked Dec 05 '25 06:12

Thomson


2 Answers

Remove the static. Just have the int array[100] = {...}; in one .cpp file, and have extern int array[100]; in the header file.

static in this context means that other translation units can't see it. That obviously conflicts with the extern directive.

like image 72
Seth Carnegie Avatar answered Dec 07 '25 20:12

Seth Carnegie


static in file scope is pretty much a declare-private directive to the assembler. It is most certainly different than static in class or function scope.

E.g. in zlib, #define LOCAL static is used.

like image 40
moshbear Avatar answered Dec 07 '25 20:12

moshbear