Header menu

_________________________________________________________________________________

Tuesday, 5 September 2017

How to use Extern in C ? / How to use same global variable in multiple files ?

If you try to declare two global variables with the same name your c compiler will print the error message duplicate variable name, which means that the compiler does not know which variable you are using at any one moment. The same type of problem occurs if you simply declare all yours global variables in each  file. you would actually be trying to create two copies of each variable. When you attempt to link your modules together you will get error message duplicate label.

The solution is to declare all of your global variables in one file and use extern-modified declaration in other files

As illustrated below:

First we create a file with global variables 

fileb.c

int a=100;
int b=200;

Now we use these global variables in other file.

file.c

#include<stdio.h>
#include<conio.h>
#include<D:\inputs\fileb.c>
extern int a;
extern int b;
int main()
{

    printf("This is main file and a & b are called from other file\n");
    printf("The value of A and B from other file is %d and %d",a,b);
    getch();
    return 0;
}

OUTPUT 

This is main file and a & b are called from other file
The value of A and B from other file is 100 and 200
 

1 comment:

  1. Online Casinos in the USA – Guide to US coin casino games
    Best Online Gambling Sites · 1. Red Dog Casino, $1,000 kadangpintar · 2. InterTops Casino, $100 · 3. Cafe Casino, 샌즈카지노 $15 · 4. Cafe Casino, 인카지노 $20

    ReplyDelete