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
Release: 2024-12-27 08:31:09
Original
631 people have browsed it

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;
Copy after login

In source1.cpp:

#include "common.h"

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

int function();

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

In source2.cpp:

#include "common.h"

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template