Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Global Variables Across Multiple Files

I have some code spread over three files and I would like to use a fourth "gloabls" file to store some physical constants such as the value of pi. This would avoid repetitive definitions of pi = 4*atan(1.0). After poking around, what I've tried is creating a global header file:

/*globals.h*/
extern double g_pi;

and a global cpp file:

/*globals.cpp*/
#include "math.h"
#include "globals.h"
double g_pi = 4*atan(1.0);

Then I include these file in my main files:

/*mainFile.cpp*/
//Include math and other libraries 
#include globals.h"
int main() {
/*
....
*/
double x = 2*g_pi
/*
....
*/
}

This gives me an undefined reference error to g_pi. I'm using a g++ compiler on Ubuntu. Hopefully its a simple fix! Your suggestions are much appreciated. If more details are necessary I'll be happy to supply them.

like image 697
fenkerbb Avatar asked Mar 14 '12 19:03

fenkerbb


1 Answers

I think the problem is that you've got #include gobals.h instead of #include globals.h. This would give you the undefined references because it isn't inserting globals.h. The C++ precompiler doesn't fail when it can't find a header file. Instead you get an undefined reference message at compilation.

like image 134
Crymson Avatar answered Oct 01 '22 02:10

Crymson