Search code examples
cvariablesstaticheader-filesstatic-initialization

Error: redefinition of "a static variable" in C header files


I have some static variables (say, var1 and var2) declared in two different files. The variables have same name in both files. Some variables (say var1) are not initialized in their declaration and some are (var2), like following.

file1.h

static bool var1;
static bool var2 = false;

file2.h

static bool var1;
static bool var2 = false;

According to my understanding, static variables are only restricted to the c files(or h files) they're declared in, so I should be safe having same variable names in multiple header files. But when I compile code, I get error "redefinition of var2", only for the variables that have been initialized.

  1. Why this error occurs only for var2 ?
  2. Is my implementation alright ?

Edit: since some mentioned to use extern keyword, I'd like to clarify that both var1 and var2 are supposed to have different values in different c files, and should only be restricted to their respective files,


Solution

  • No. The multiple declaration of var1 is okay, but the multiple definition of var2 is not. You can't initialize a variable twice...even if the values are the same.

    I solve problems like this using preprocessor guards, such as:

    #if !defined(MY_APP__VARS_DEFINED)
    static int var1, var2=0;
    #define MY_APP__VARS_DEFINED
    #endif
    

    Even then, I don't recommend duplicating the definitions in multiple header files. It's a maintenance problem. Sooner or later, someone is likely to change that initial value in one header and not find all other headers it's defined in. It also makes renaming ("refactoring") harder. (...and violates the DRY Principle.)

    You might want to rethink your design, though. Global variables usually lead to brittle applications; harder to maintain and easy to break.