views:

228

answers:

2

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

Thanks

+5  A: 

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.

R Samuel Klatchko
+1  A: 

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.

Ben Voigt