Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable in a Header File

Static variable has file scope. Say I have two following files:

  • file1.h
  • file1.cpp
  • file2.h
  • file2.cpp

I have declared static variable say static int Var1 in both the header files. Both file1.h and file2.h are included in main.cpp file.

I did this since the static variable will have file scope so it won't conflict each other. But after compilation I found it is showing conflict.

Now static variable is behaving like a extern variable. On the other hand if I declare the static variable in both .cpp files, it compiles well.

I am unable to understand this behavior.

Can any body explain how scope and linkage are working in this scenario.

like image 267
Vikram Ranabhatt Avatar asked Feb 18 '11 11:02

Vikram Ranabhatt


People also ask

Can we have static variable in header file?

Yes there is difference between declaring a static variable as global and local. If it is local, it can be accessed only in the function where it's declared. But if it is global, all functions can access it.

Can a variable be defined in a header file?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.

What happens if we include a static global variable in a header file?

Basically, each source file together with all included header files is a single translation unit. So If you have a static variable in a header file then it will be unique in each source file (translation unit) the header file is included in.

What is static variable can static variable be declared in header file in C?

Static variables have the static scope and are defined once and used multiple times. Non-static variables have the dynamic scope and are defined and used each time the variable is needed. Static variables are declared in the header file and non-static variables are declared in the source file.


1 Answers

Static variables have translation unit scope (usually a .c or .cpp file), but an #include directive simply copies the text of a file verbatim, and does not create another translation unit. After preprocessing, this:

#include "file1.h"
#include "file2.h"

Will turn into this:

/* file1.h contents */
static int Var1;

/* file2.h contents */
static int Var1;

Which, as you know, is invalid.

like image 177
moatPylon Avatar answered Oct 01 '22 19:10

moatPylon