Friday, December 4, 2020

, ,

Understand the extern in c with extern c example

  •  extern keyword in C is used when we have multiple source file and we want to shear the variable among those files.
  • Or when we prefixing a global variable with the extern keyword in C that's mean we are telling to the compiler that the variable is already defined in other file.
  • That's means don't allocate any memory for the same variable twice.

What is use of extern in c

extern can be use in two type :-

  • A variable declaration statement 

  • A variable definition statement 

declaration statement for extern

int a;
 
char* ch;

With the help of extern in c we can tell to the compiler that these variables already exist somewhere so don't allocate any memory for these variables.

There is an another way to defining a variable,where you can allocate storage for the given variable. 

// Defining a
int a = 11;
 
// Defining ch, even if it is NULL
char* ch = NULL;

let's check the use of extern in c. You can use this extern keyword only for declaring a global variable.

// Allowed. Variable declaration
extern int a;
 
// Not allowed. extern with variable definition
extern int b = 5;

Let's know about the use of extern in c with example

Assume we have to files 

  •     file1x.c, file1x.h
  •     file2x.c file2x.h.

And a main.c which is an drive program.

Here we have a global variable which is called int file1_var defined in file1x.c.

Here we use extern in extern c example for sharing the same variable for file2x.c.

Here the extern c example : -

// file1.h
// Contains function prototypes for functions of file1.c
 
int addition_1(int a, int b);


// file1.c
// Contains function definition for addition_1()
#include "file1.h"
#include <stdio.h>
 
int file1_var = 100;
 
int addition_1(int a, int b) {
    file1_var = file1_var + 100;
    printf("Inside file1.c addition(). file1_var = %d\n", file1_var);
    return a + b;
}


As you can see that two files share a variable file1_var with the help of extern keyword and this variable will be update when the addition() functions gets called.

Now let's write the main.c program with both the header files file1x.h and file2x.h



#include "file1.h"
#include "file2.h"
#include <stdio.h>
 
// We can also use the file1_var reference here!
extern int file1_var;
 
// We must have only one main() reference
// Since this is our driver program, the main function must be only here
int main() {
    int res1 = addition_1(10, 20);
    int res2 = addition_2(30, 40);
    printf("file1_var = %d\n", file1_var);
    return 0;
}

Output extern c example

Output extern c example
Output extern c example


0 comments:

Post a Comment