Home >Backend Development >C++ >How Can I Efficiently Share Global Variables Across Multiple Source Files?

How Can I Efficiently Share Global Variables Across Multiple Source Files?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 08:31:09682browse

How Can I Efficiently Share Global Variables Across Multiple Source Files?

Accessing Global Variables Across Multiple Source Files

In the given scenario, you have two source files that require access to a shared variable named global. Determining the most efficient way to achieve this is crucial.

The solution lies in declaring global as extern within a header file that both source files include. This approach ensures that the variable is visible to all source files but defined in only one.

In the header file (common.h):

extern int global;

In source1.cpp:

#include "common.h"

int global; // Define global in only one source file

int function();

int main() {
    global = 42;
    function();
    return 0;
}

In source2.cpp:

#include "common.h"

int function() {
    if (global == 42)
        return 42;
    return 0;
}

By utilizing this approach, both source1.cpp and source2.cpp can access the shared variable global without creating compilation errors or unexpected behavior.

The above is the detailed content of How Can I Efficiently Share Global Variables Across Multiple Source Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn