Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
C++ Header File Without Extern
2.1.
C++
3.
C++ Extern Without the Header File
3.1.
C++
4.
Constant and Extern
5.
Extern and static
5.1.
C++
6.
When to use C++ Extern
6.1.
1. Sharing global variables
6.2.
2. Separating declaration and definition
6.3.
3. Resolving circular dependencies
6.4.
4. Linking with external libraries
7.
Examples of C++ Extern
7.1.
Example 1: Sharing a variable between source files 
7.2.
C++
7.3.
Example 2: Separating declaration and definition
7.4.
C++
8.
Frequently Asked Questions
8.1.
Can extern be used with variables of any data type?
8.2.
Is it necessary to use extern when declaring functions in header files?
8.3.
Can extern be used with constants?
9.
Conclusion
Last Updated: Aug 5, 2024
Easy

Extern in C++

Author Pallavi singh
0 upvote

Introduction

Extern is a keyword in C++ that allows you to declare a variable or function in one source file and use it in another. It helps to extend the visibility of variables and functions across multiple files in a program. With the help of an extern, you can share data between different parts of your code without having to pass the data as arguments to functions. 

Extern in C++

This article will discuss the concept of extern in C++, its use with and without header files, and how it interacts with constants and static variables. 

C++ Header File Without Extern

In C++, you can declare variables and functions in a header file without using the extern keyword. When you include the header file in your source files, the variables and functions declared in the header file become available for use.

For example : 

  • C++

C++

// myheader.h

#ifndef MYHEADER_H

#define MYHEADER_H

int myVariable = 42;

void myFunction() {

   // Function implementation

}

#endif

// main.cpp

#include "myheader.h"

#include <iostream>

int main() {

   std::cout << myVariable << std::endl;

   myFunction();

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

42


In this example, the header file "myheader.h" declares a variable myVariable and a function myFunction() without using extern. The header file is included in the main source file "main.cpp", making myVariable and myFunction() accessible in the main() function.

C++ Extern Without the Header File

In C++, you can also use the extern keyword to declare variables and functions in one source file and use them in another without including a header file. This is useful when you want to share data between source files without the overhead of creating and including a separate header file.

For example : 

// file1.cpp

#include <iostream>

int myVariable = 42;

void myFunction() {
    std::cout << "Hello from myFunction!" << std::endl;
}

 

// file2.cpp

  • C++

C++

#include <iostream>

extern int myVariable;

extern void myFunction();

int main() {

   std::cout << myVariable << std::endl;

   myFunction(); // Output: Hello from myFunction!

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output: 

42


In this example, "file1.cpp" defines the variable myVariable and the function myFunction(). The extern keyword is not used in this file.

In "file2.cpp", the extern keyword is used to declare myVariable and myFunction() without providing their definitions. This tells the compiler that these entities are defined elsewhere in the program.

When you compile and link these files, the linker resolves the external references and connects the declarations in "file2.cpp" with the definitions in "file1.cpp".

Constant and Extern

In C++, you can use the extern keyword in conjunction with the const keyword to declare global constants that can be shared across multiple files.

For example : 

// constants.cpp
const int MAX_SIZE = 100;
// main.cpp
#include <iostream>
extern const int MAX_SIZE;
int main() {
    int arr[MAX_SIZE];
    std::cout << "Array size: " << MAX_SIZE << std::endl;
    // Use the array...
    return 0;
}


In this example, the constant MAX_SIZE is defined in the file "constants.cpp". The extern keyword is used in the "main.cpp" file to declare that MAX_SIZE is defined elsewhere.

When we use extern with const, you can define global constants in one file and use them in other files without violating the one definition rule (ODR). The ODR states that a variable or function should have only one definition in a program.

Note: It's important to remember that when we use extern with const, the constant must be initialized in the file where it is defined. This is because the extern declaration in other files only refers to the constant's declaration, not its definition.

Extern and static

In C++, the extern and static keywords have opposite effects when used with variables and functions.

When a variable or function is declared as static, it means that the variable or function has internal linkage and is only accessible within the same source file where it is defined. On the other hand, when a variable or function is declared as an extern, it has an external linkage and can be accessed from other source files.

For example : 

// file1.cpp

static int staticVariable = 10;
extern int externVariable = 20;
static void staticFunction() {
    // Function implementation
}
void externFunction() {
    // Function implementation
}


// file2.cpp

  • C++

C++

#include <iostream>

extern int externVariable;

extern void externFunction();

int main() {

   std::cout << externVariable << std::endl;

   externFunction();

 // std::cout << staticVariable << std::endl; // Error: staticVariable is not accessible

   // staticFunction(); // Error: staticFunction is not accessible

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code


Output

20
staticVariable is not accessible
staticFunction is not accessible


In this example, staticVariable and staticFunction() are declared as static in "file1.cpp", which means they are only accessible within "file1.cpp". Attempting to access them from "file2.cpp" will result in a compilation error.

On the other hand, externVariable and externFunction() are declared as extern in "file1.cpp", which means they can be accessed from other source files. In "file2.cpp", we can use externVariable and call externFunction() without any issues.

The static keyword is often used to limit the scope of variables and functions to a single source file, preventing naming conflicts and providing encapsulation. The extern keyword, on the other hand, is used to extend the visibility of variables and functions across multiple source files.

When to use C++ Extern

The extern keyword in C++ is used in various scenarios to extend the visibility and accessibility of variables and functions across multiple source files. 

Let’s see some common situations where an extern is used:

1. Sharing global variables

 When you have a global variable that needs to be accessed from multiple source files, you can declare the variable as an extern in one file and define it in another file. This allows the variable to be shared across the files.

Example:

   // file1.cpp
   int globalVariable = 42;
 // file2.cpp
   extern int globalVariable;
  void function() {
       std::cout << globalVariable << std::endl;
   }

2. Separating declaration and definition

 extern can be used to separate the declaration of a variable or function from its definition. This is useful when you have a large project with multiple source files and want to keep the declaration in a header file and the definition in a separate source file.

Example:

   // header.h
   extern void myFunction();
   // source.cpp
   #include "header.h"
   void myFunction() {
       // Function implementation
   }

3. Resolving circular dependencies

 When you have circular dependencies between header files, where two or more header files include each other, you can use an extern to break the dependency cycle.

 Example:

   // header1.h
   #ifndef HEADER1_H
   #define HEADER1_H
   extern int variable;
   #endif
   // header2.h
   #ifndef HEADER2_H
   #define HEADER2_H
   #include "header1.h"
   void function();
   #endif

4. Linking with external libraries

 When linking your C++ program with external libraries, you can use extern to declare functions or variables that are defined in the library.

Example:

   extern "C" {
       // Declare functions from an external C library
       void externalFunction();
   }
   int main() {
       externalFunction(); // Call the function from the external library
       return 0;
   }


These are some of the common scenarios where extern is used in C++. It allows you to extend the visibility of variables and functions beyond a single source file, enabling modular programming and code reuse.

Examples of C++ Extern

Example 1: Sharing a variable between source files
 

  • C++

C++

// file1.cpp
#include <iostream>

int count = 0;

void incrementCount() {
count++;
}

void printCount() {
std::cout << "Count: " << count << std::endl;
}

// file2.cpp
extern int count;
extern void incrementCount();
extern void printCount();

int main() {
incrementCount();
incrementCount();
printCount();
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output: 

Count: 2


In this example, the variable count is defined in "file1.cpp" and declared as extern in "file2.cpp". The functions incrementCount() and printCount() are also declared as extern in "file2.cpp". This allows "file2.cpp" to access and modify the count variable and call the functions defined in "file1.cpp".

Example 2: Separating declaration and definition

  • C++

C++

// mathutils.h
#ifndef MATHUTILS_H
#define MATHUTILS_H

extern int add(int a, int b);
extern int subtract(int a, int b);

#endif

// mathutils.cpp
#include "mathutils.h"

int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {
return a - b;
}

// main.cpp
#include <iostream>
#include "mathutils.h"

int main() {
int result1 = add(5, 3);
int result2 = subtract(10, 7);

std::cout << "Addition: " << result1 << std::endl;
std::cout << "Subtraction: " << result2 << std::endl;

return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Addition: 8
Subtraction: 3

 

In this example, the functions add() and subtract() are declared as extern in the header file "mathutils.h" and defined in the source file "mathutils.cpp". The "main.cpp" file includes the "mathutils.h" header and can use the functions declared in it. This separation of declaration and definition allows for a cleaner and more modular code structure.

Frequently Asked Questions

Can extern be used with variables of any data type?

Yes, extern can be used with variables of any data type, including built-in types like int, float, char, and user-defined types like structures and classes.

Is it necessary to use extern when declaring functions in header files?

No, it is not necessary to use extern when declaring functions in header files. Functions are extern by default, so you can declare them without the extern keyword.

Can extern be used with constants?

Yes, extern can be used with constants. When declaring a constant with extern, it is important to ensure that the constant is initialized in exactly one source file to avoid multiple definitions.

Conclusion

In this article, we have learned about the extern keyword in C++ and how to use this in extending the visibility and accessibility of variables and functions across multiple source files. We explained how an extern can be used with and without header files, how it interacts with constants and static variables, and when it is typically used. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass