Home >Backend Development >C++ >How to Share Global Variables Between Multiple C/C Files?

How to Share Global Variables Between Multiple C/C Files?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 17:13:12459browse

How to Share Global Variables Between Multiple C/C   Files?

Accessing Global Variables Across Multiple Files in C/C

When working with multiple source files in a C/C program, it is often necessary to share global variables between them. This can be achieved through various methods, including static and extern declarations or using a header file.

Consider the example provided:

source1.cpp:

int global;

int function();

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

source2.cpp:

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

Solution 1: Header File with extern

The preferred approach is to declare the global variable extern in a header file included by both source files:

common.h:

extern int global;

source1.cpp:

#include "common.h"

int global;  // Only define it in one file

int function();

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

source2.cpp:

#include "common.h"

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

This ensures that the declaration of global is visible to both source files, but only one definition of it is present (in source1.cpp). The extern keyword specifies that the variable is declared elsewhere.

The above is the detailed content of How to Share Global Variables Between Multiple C/C 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