🔧Connect multiple C++ Files
Here is how to connect multiple c++ file:
Here is a code example using multiple files:
// File: math_operations.h
#ifndef MATH_OPERATIONS_H
#define MATH_OPERATIONS_H
// Function declarations
int add(int a, int b);
int subtract(int a, int b);
// Variable declaration with external linkage
extern int globalValue;
#endif // MATH_OPERATIONS_H// File: math_operations.cpp
#include "math_operations.h"
// Function definitions
int add(int a, int b) {
    return a + b;
}
int subtract(int a, int b) {
    return a - b;
}
// Variable definition
int globalValue = 10;// File: main.cpp
#include <iostream>
#include "math_operations.h"
int main() {
    std::cout << "Sum: " << add(5, 3) << std::endl;
    std::cout << "Difference: " << subtract(10, 4) << std::endl;
    std::cout << "Global value: " << globalValue << std::endl;
    return 0;
}Now, let's break down how these files are linked:
Header files and source files:
math_operations.his a header file containing function declarations and an external variable declaration.math_operations.cppis a source file with the implementations of the functions declared in the header.main.cppis the main source file that uses the functions defined inmath_operations.
#include directive:
math_operations.cppincludesmath_operations.hto ensure the function implementations match the declarations.main.cppincludesmath_operations.hto access the function declarations and the external variable.
External linkage:
globalValueis declared withexternin the header, making it accessible across multiple files.It's defined in
math_operations.cppand can be used inmain.cpp.
Function declarations and definitions:
Functions are declared in
math_operations.hand defined inmath_operations.cpp.This allows
main.cppto use these functions by including only the header file.
To compile and link these files, you would use a command like:
g++ main.cpp math_operations.cpp -o programThis compiles both source files and links them together into an executable named "program".
The #ifndef, #define, and #endif in the header file create an "include guard" to prevent multiple inclusions of the same header, which can cause compilation errors.
Last updated