Google News
logo
Embedded C - Interview Questions
How to use a variable in a source file which is defined in another source file?
extern keyboard can be to declare a variable which allows accessing the variable in another file.
 
Let’s understand how it will possible?
 
file1.c
/*include header file "file2.h"
where variable is declare*/ 
#include "file2.h"

...
/*Access the variable, where it is 
Required*/
if(flgUSB){

    ...;
}

file2.c
/*define variable in global scope*/
unsigned char flgUSB=0;
/*while defining a variable, 
you can assign a default value to it*/

file2.h
/*declare variable in global scope*/
extern unsigned char flgUSB;
/*do not use default value here, it will generate an error*/
Explanation :
 
If the variable is defined in "file2.c" and you want to access it in "file1.c", then you have to create a header file like "file2.h".
 
Declare the variable using extern in the header file and then include it file in "file1.c" or wherever you want to access the variable.
Advertisement