Monday, 23 April 2018

c++ - Global Variable within Multiple Files



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?



Answer



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;
}


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...