Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 212
coelhudo Avatar asked Mar 16 '10 23:03

coelhudo


People also ask

Can a variable be Redeclared in C?

C allows a global variable to be declared again when first declaration doesn't initialize the variable.

What is Redeclaration in C?

Redeclaration: In C, you cannot redeclare a variable within the same scope. However, you can overwrite a global variable's declaration locally. Example. #include<stdio.h> void dummy();

Can global variables be declared anywhere in C?

Assuming your variable is global and non static. You need to declare it in a header file.

What is type mismatch error in C?

The type of an actual argument does not match the corresponding formal parameter at a subroutine call. This error usually indicates that the function declaration in force at the call site is inconsistent with the function definition.


1 Answers

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.

like image 89
R Samuel Klatchko Avatar answered Nov 15 '22 08:11

R Samuel Klatchko