What is the use of extern in c/c++?

The extern keyword is used to tell the compiler that a data object is declared in a different *.cpp or *.c file. So there wont be any new memory is allocated for these variables. Check the below example and understand the working.

//file1.cpp
#include <iostream.h>
 
int x;
extern void func2();
 
void func1(void)
{
        x = x + 100;
        cout<<"x in func1 = "<< x << endl;
}
 
int main(void)
{
        x = 10;
        cout<<"x in main function = "<< x << endl;
        func1(); // calls func1 
        func2(); // calls func2 from file2
}
//file2.cpp
#include <iostream.h>
extern int x;
void func2(void)
{
        x = x + 300;
        cout<<"x in file2 = "<< x << endl;
}

Output:

x in main function = 10
x in func1 = 110
x in file2 = 410

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in