coelhudo
coelhudo

Reputation: 5080

Compile redeclaration error of global variable in C++, but not in C

Suppose that I have those three files:

a.h

//a.h header
#include <stdio.h>
int int_variable;

void a_f()
{
   printf("int_variable: %d\n", int_variable)
   int_variable++;
}

b.h

//b.h header
#include <stdio.h>
int int_variable;

void b_f()
{
   printf("int_variable: %d\n", int_variable)
   int_variable++;
}

main.c

//main.c
#include "a.h"
#include "b.h"

int main()
{
   a_f();
   b_f();
   return 0;
}

Why compiling in C++ generates redefinition error, but in C doesn't? I am C++ developer, then in C++ makes sense to me, but why in C this is not an error?

When I executed the C generated code, the output was:

int variable: 0

int variable: 1

Upvotes: 9

Views: 3949

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

Global variables in header file should only be used along with the "extern" modifier. No exceptions. Forward declare your variable in one or more header files (preferably just one), then define it in exactly one compilation unit.

Upvotes: 2

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

In C, the two variables are actually combined into a single variable because neither is explicitly initialized.

If you change both your h files to:

// a.h
int int_variable = 0;

and:

// b.h
int int_variable = 0;

you will get a redefinition error.

Upvotes: 7

Related Questions