Home > Enterprise >  How to let compiler catch inconsistent type of global variables in two source files of C
How to let compiler catch inconsistent type of global variables in two source files of C

Time:03-01

my1.c

float e;
void f1(){ e=3.0;}

my2.c

#include <stdio.h>
int e=0;
void f1();
void main(){
  printf("%d in main \n", e);
  f1();
  printf("%d in main \n", e);
}

Here the global variable e is mistakenly declared as float and int in two source files.

How to let the linker raise error for this inconsistency?

CodePudding user response:

We mitigate this risk using header files, not the linker. Anything referred to in multiple translation units should be declared in one header file:

MyGlobal.h:

extern float e;

Any file that uses it should include the header file:

main.c:

#include "MyGlobal.h"

…
    printf("e is %f.\n", e);

Exactly one file should define it, and include the header file:

MyGlobal.c:

#include "MyGlobal.h"

float e = 0;

By using a header file, the declaration is identical in all translation units. Because the source file that defines the identifier also includes the header file, the compiler reports any inconsistency.

Any external declarations (that are not definitions) outside of header files are suspect and should be avoided.

CodePudding user response:

1.c

static float e;
void f1(){ e=3.0;} 

2.c

#include <stdio.h>
static int e=0;
void f1();
void main()
{
printf("%d in main \n", e);
f1();
printf("%d in main \n", e);
}
  • Related