Thomson
Thomson

Reputation: 21704

How to share one static variable with multiple translation unit?

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?

Upvotes: 3

Views: 3417

Answers (3)

Craig Mc
Craig Mc

Reputation: 189

Instead of making the variable global, consider leaving it static and adding public accessors and modifiers to it. It's not a great thing to directly couple to naked variables in other modules.

Upvotes: 2

moshbear
moshbear

Reputation: 3322

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.

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75150

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.

Upvotes: 14

Related Questions