What happens if you define a variable in a header file but do not use the extern keyword?

If you define a variable in a header file without using the extern keyword, it can lead to multiple definition errors during the linking phase of compilation. This occurs because the header file is typically included in multiple source files, causing the variable to be defined in each translation unit (source file) that includes the header.

How it works?

Variable Definition in Header

When a variable is defined in a header file, for example:

// header.h
int counter = 0;

Including header.h in multiple source files like this:

#include "header.h"

results in each source file defining a separate counter variable.

YouTube

Linker Error

The linker expects only one definition of a variable across the entire program. Since the variable is defined in multiple source files, the linker will generate an error similar to:

multiple definition of `counter`

Solution with extern keyword

To avoid this, the variable should be declared in the header file using the extern keyword and defined in exactly one source file:

// header.h
extern int counter; // Declaration (no definition)
// source.cpp
#include "header.h"
int counter = 0; // Single definition

Why extern keyword matters

Without extern, every inclusion of the header creates a new variable, violating the “One Definition Rule” (ODR). Using extern ensures the variable is only declared in the header, while its memory allocation is centralized in one source file.

extern keyword

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top