Global Variable within Multiple Files

C++

C++ Problem Overview


I have two source files that need to access a common variable. What is the best way to do this? e.g.:

source1.cpp:

int global;

int function();

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

source2.cpp:

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

Should the declaration of the variable global be static, extern, or should it be in a header file included by both files, etc?

C++ Solutions


Solution 1 - C++

The global variable should be declared extern in a header file included by both source files, and then defined in only one of those source files:

>common.h

extern int global;

>source1.cpp

#include "common.h"

int global;

int function(); 

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

>source2.cpp

#include "common.h"

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

Solution 2 - C++

You add a "header file", that describes the interface to module source1.cpp:

source1.h

#ifndef SOURCE1_H_
#define SOURCE1_H_

extern int global;

#endif

source2.h

#ifndef SOURCE2_H_
#define SOURCE2_H_

int function();

#endif

and add an #include statement in each file, that uses this variable, and (important) that defines the variable.

source1.cpp

#include "source1.h"
#include "source2.h"

int global;     

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

source2.cpp

#include "source1.h"
#include "source2.h"

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

While it is not necessary, I suggest the name source1.h for the file to show that it describes the public interface to the module source1.cpp. In the same way source2.h describes what is public available in source2.cpp.

Solution 3 - C++

In one file you declare it as in source1.cpp, in the second you declare it as

extern int global;

Of course you really don't want to be doing this and should probably post a question about what you are trying to achieve so people here can give you other ways of achieving it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkaykunView Question on Stackoverflow
Solution 1 - C++e.JamesView Answer on Stackoverflow
Solution 2 - C++harperView Answer on Stackoverflow
Solution 3 - C++PatrickView Answer on Stackoverflow