Saturday, April 22, 2017

Extern Keyword in C

extern allows one module of your program to access a global variable or function declared in another module of your program. You usually have extern variables declared in header files. extern is used to let other C files or external components know this variable is already defined somewhere.

Using extern is only of relevance when the program you're building consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, such as file2.c.

It is important to understand the difference between defining a variable and declaring a variable:

1) A variable is defined when the compiler allocates the storage for the variable.

2) A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.

You may declare a variable multiple times (though once is sufficient); you may only define it once within a given scope.

Best way to declare and define global variables

Although there are other ways of doing it, the clean, reliable way to declare and define global variables is to use a header file file3.h to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable. For each program, one source file (and only one source file) defines the variable. Similarly, one header file (and only one header file) should declare the variable.

file3.h
extern int global_variable;  /* Declaration of the variable */

file1.c
#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */

/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */
int increment(void) { return global_variable++; }

file2.c
#include "file3.h"
#include "prog1.h"
#include

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

prog1.h
extern void use_it(void);
extern int increment(void);

prog1.c
#include "file3.h"
#include "prog1.h"
#include

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}

references:
http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c

No comments:

Post a Comment