I agree with the comments here advising against the use of global variables, they can cause problems related to initialization order, they can create problems with thread safety, they pollute the namespace, etc.
The idiomatic way of dealing with globals in c++ is to put them in a struct (as you alluded to) or to put them in a namespace. You can read more about that here.
However, if you must use globals (in c++ you would say variables and functions at global scope
) here's a simple example patterned after your code:
makefile
main: main.cpp a.cpp profile.cpp my_globals.h
g++ -O3 -o main main.cpp a.cpp profile.cpp
clean:
$(RM) main
my_globals.h
// This is a header file and should only contain declarations
extern char Name[10]; // declaration of Name variable
extern void use_global(int); // declaration of use_global function
main.cpp
#include "my_globals.h"
int main(int argc, char * argv[])
{
use_global(10); // use of use_global function
return 0;
}
a.cpp
#include "my_globals.h"
#include <iostream>
using std::cout;
using std::endl;
void use_global(int id) { // definition of use_global function
if(id==10)
{
cout<<Name<<endl; // use of Name global variable
}
}
profile.cpp
#include "my_globals.h"
char Name[10]="John"; // definition of Name variable
You build it
$ make
g++ -O3 -o main main.cpp a.cpp profile.cpp
$
and you run it:
$ ./main
John
$