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
C allows a global variable to be declared again when first declaration doesn't initialize the variable.
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();
Assuming your variable is global and non static. You need to declare it in a header file.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With