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
Release: 2024-12-07 17:13:12
Original
458 people have browsed it

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

source2.cpp:

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

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

source1.cpp:

#include "common.h"

int global;  // Only define it in one file

int function();

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

source2.cpp:

#include "common.h"

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

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!

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