Open In App

How Do I Use ‘extern’ to Share Variables Between Source Files?

Last Updated : 28 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, extern is a keyword that helps in sharing variables, and functions declared in one file to all the other files. In this article, we will learn how we can use the extern keyword to share variables between source files in C++.

How to Use Extern Keyword in C++

The extern keyword in C++ extends the visibility of a variable present in a file so that it can be accessed in other files as well. The extern keyword informs the compiler that the variable is defined in another source file and should be accessed accordingly.

Syntax:

extern DataType VariableName;

This syntax is only the declaration of the variable. It should be initialized before use.

C++ Program to Use Extern to Share Variables Between Source Files

Let us consider two files source.cpp and destination.cpp. We will define the variables that we want to share in the source.cpp file and then we will access them in the destination.cpp using the extern keyword. Make sure that both files are present in the same file path or else you will face an error.

source.cpp:

C++




// Source.cpp file
  
#include <iostream>
using namespace std;
  
// Declare the variables you want to share
int sharedVariable1 = 100;
int sharedVariable2 = 200;


Now, access the shared variables

destination.cpp:

C++




// C++ program  to share variables between source files
// using extern keyword
// include the file where shared variables are defined.
  
#include "source.cpp"
#include <iostream>
using namespace std;
  
// use already declared Shared variable from source.cpp
// using extern keyword
extern int sharedVariable1;
extern int sharedVariable2;
int main()
{
    // print the shared variables
    cout << "Shared Variables from another source file are "
            ": "
         << sharedVariable1 << " , " << sharedVariable2
         << endl;
}


Output

Shared Variables from another source file are : 100 , 200

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads