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

c, c++, compilation, compiler-errors, global-variables

Solution

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.

Problem

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

Original source

Related problems