Search code examples
c++variablesstaticheader

Why can't a non-static variable reside in a header file?


Take for example:

// myheader.h
static int myStaticVar = 0;
// If we remove 'static' the compiler will throw linker error.

void DoStuff();

// and myheader.cpp, and main.cpp;  etc

This is how I would explain it:

Static variables do not have external linkage, and when we compile without 'static' we are "including" the static variable (which is global here) in every file, which create duplicates and linker will throw an error since multiple declaration is not allowed.

Is there any better way to explain this? Thanks.

PS: Are we suppose to have static variables (not talking about members) in header file?


Solution

  • Why can't a non-static variable reside in a header file?

    Because it breaks the One Definition Rule(ODR).
    When you include the header file containing a non-static variable, the declaration of the variable gets pasted in each source file where it is included. Thus, you end up having more than one definition of a variable, in the same Translation Unit, this violates the ODR, and hence, the linker will give you linking errors.

    How to explain static variables declared in header files?

    When you declare a static variable in a header file, a copy of the variable gets created in each Translation Unit where the header file is included.

    Declaring a static variable in the header file will not give you multiple definition errors, but it does not achieve your purpose of having a global variable whose value is shared across all files which access it.

    You may think that since you are using a global static variable, its value will be retained across different files, but as mentioned above, each Translation Unit has its own copy of the variable, and it does not achieve what you think you are achieving.

    Are we suppose to have static variables (not talking about members) in header file?

    No, Never!

    How do you declare and define global variables?

    You need to use the extern keyword.

    Add the extern declaration of the variable in a header file. The header should be included by the one source file that defines the variable, and by all the source files that reference the variable. Only one source file should define the variable. Also, only one header file should declare the variable.

    filename.h

    extern int gVariable;  /* Declaration */ 
    

    file1.cpp

    #include "filename.h"  
    
    /* Definition */ 
    int gVariable = 37;    
    
    void doSomething(void) 
    { 
        return gVariable++; 
    } 
    

    file2.cpp

    #include "filename.h" 
    #include <stdio.h>  
    void doSomethingWithGlobal(void) 
    {     
        printf("Global variable: %d\n", gVariable++); 
    }