0

I am trying to declare an variable x in a file demo_f1.c and use it in two files demo_f2.c and demo_f3.c having two functions void f2() and void f3(), respectively.

I have a driver program that uses the variable x and both of these functions, but it gives me an error while I try to compile the driver program.

demo_f1.c

int x=2;

demo_f2.c

#include"C:\TC\BIN\demo_f1.C"

void f2()

{

    extern int x;

    printf("In f2 x:%d\n",x);

}

demo_f3.c

#include"C:\TC\BIN\demo_f1.C"

void f3()

{

    extern int x;

    printf("In f3 x:%d\n",x);

}

Driver.c

#include"stdio.h"
#include"conio.h"
#include"C:\TC\BIN\demo_f1.C"
#include"C:\TC\BIN\demo_f2.C"
#include"C:\TC\BIN\demo_f3.C"
void main()

{

    clrscr();

    printf("In main program,x:%d\n",x);

    f2();

    f3();

    getch();

}

The error:

Compiling C\TC\BIN\Driver.C:
Error C\TC\BIN\DEMO_F1.C 1: Variable 'x' is initialized more than once
Error C\TC\BIN\DEMO_F1.C 1: Variable 'x' is initialized more than once

Why am I getting this error? How can I correct it?

Cel Skeggs
  • 1,827
  • 21
  • 38

2 Answers2

0

To make your code compile, you simply need to remove extern int x; from f2() and f3(). For a more complete answer read How do I use extern to share variables between source files in C? as grahamj42 suggests.

Community
  • 1
  • 1
Alastair Brown
  • 1,598
  • 8
  • 12
0

You are including demo_f1.c three times in driver.c, one directly and two indirectly through demo_f2.c and demo_f3.c. In consequence, the compiler finds three times the line "int x=2;"

You can use the mechanism with #ifndef typically used in header files. Make demo_f1.c like this:

#ifndef DEMO_F1_C
#define DEMO_F1_C
int x=2;
#endif

Alternatively, to avoid including the .c file, you could have:

demo_f1.h

#ifndef DEMO_F1_H
#define DEMO_F1_H
extern int x;
#endif

demo_f1.c

#include "demo_f1.h"
int x = 2;

And the other files would include demo_f1.h.

Miguel Muñoz
  • 326
  • 1
  • 6