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?
            Asked
            
        
        
            Active
            
        
            Viewed 3,043 times
        
    3
            
            
         
    
    
        Thomson
        
- 20,586
- 28
- 90
- 134
- 
                    At what point did you decide that you needed to "make the array static"? – Kerrek SB Nov 10 '11 at 02:10
- 
                    1@KerrekSB I think most people think that a global `static` variable would mean the same thing as making a class variable `static` or making a local variable in a function `static`. It's an understandable mistake, but it doesn't even do nearly that. – Seth Carnegie Nov 10 '11 at 02:13
- 
                    see http://stackoverflow.com/questions/4615192/why-does-the-static-keyword-have-so-many-meanings-in-c-and-c – c-urchin Nov 10 '11 at 15:31
3 Answers
14
            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.
 
    
    
        Seth Carnegie
        
- 73,875
- 22
- 181
- 249
2
            
            
        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.
 
    
    
        moshbear
        
- 3,282
- 1
- 19
- 33
- 
                    3What has the assembler to do with anything? Did you mean the "linker"? – Kerrek SB Nov 10 '11 at 02:20
- 
                    1No, assembler. The assembler creates the symbol table. I'm certain `gcc -c` and similar don't involve the linker. – moshbear Nov 10 '11 at 02:27
- 
                    1I see. In any event, there's no "assembly stage" in the language standard, only "linkage types" :-) – Kerrek SB Nov 10 '11 at 02:38
2
            
            
        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.
 
    
    
        Craig Mc
        
- 179
- 1
- 2
- 
                    Through the 2023 retrospectoscope this seems like pretty bad advice :) – Craig.Feied Jan 15 '23 at 22:03