C++ Extern Function Example
What is an Extern Function?
In C++, an extern
function is a way to declare a function that is defined in a different source file. This allows you to use the function in multiple files without having to redefine it each time.
How It Works:
-
Declaration: You declare the function using the
extern
keyword in the header file. This declaration tells the compiler that the function exists but does not define it.// my_functions.h extern int add(int a, int b);
-
Definition: The function is then defined in a separate source file.
// my_functions.cpp int add(int a, int b) { return a + b; }
-
Usage: You can use the function in any source file that includes the header file containing the
extern
declaration.// main.cpp #include "my_functions.h" int main() { int result = add(5, 3); std::cout << "Result: " << result << std::endl; // Output: Result: 8 return 0; }
Why Use Extern Functions?
- Code Organization: Separating function definitions into different files improves code organization and maintainability.
- Modularity: You can easily reuse the function in multiple projects.
- Code Sharing: Extern functions facilitate code sharing between developers and teams.
Example:
Here's a complete example demonstrating the use of extern functions.
my_functions.h:
extern int add(int a, int b);
my_functions.cpp:
int add(int a, int b) {
return a + b;
}
main.cpp:
#include
#include "my_functions.h"
int main() {
int result = add(5, 3);
std::cout << "Result: " << result << std::endl;
return 0;
}
Explanation:
- my_functions.h: Declares the
add
function asextern
. - my_functions.cpp: Defines the
add
function. - main.cpp: Includes the header file
my_functions.h
to access theadd
function. The program then uses theadd
function to calculate and print the result.
Note:
When using extern functions, ensure that the function definition and the extern
declaration have the same name, return type, and parameters.