C++ Extern Function Example

3 min read Jul 03, 2024
C++ Extern Function Example

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:

  1. 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); 
    
  2. Definition: The function is then defined in a separate source file.

    // my_functions.cpp
    int add(int a, int b) {
        return a + b;
    }
    
  3. 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:

  1. my_functions.h: Declares the add function as extern.
  2. my_functions.cpp: Defines the add function.
  3. main.cpp: Includes the header file my_functions.h to access the add function. The program then uses the add 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.

Latest Posts


Featured Posts