Sign in to follow this  

Problem with 'extern'

Recommended Posts

1) I have my globals.h file, where I store everything that needs to be global :)
#include <SDL\SDL.h>
#include <iostream>
#include <fstream>
#include <SDL\SDL_opengl.h>
extern int lol;

#include <vector>
#include <cmath>
#include "vector_class.h"
#include "matrix_class.h"
#include "tga.h"
#include "model.h"
#include "camera.h"
#include "terrain.h"
#include "camera.h"

as you can see, I'm trying to implement multitexturing. Now, when I try to compile my whole code, it bugs me with "redefinition of ..." errors for these 3 variables. What makes me wonder, it doesn't display any errors for int variable. So my question - anyone have any idea how to avoid it? I have inclusion guards for globals.h in every header file :S 2) Where is that article, I can't find it now, it was a big one (on gamedev) how to organise code and how to fight with linking errors. Could anyone post a link to it? thx

Share this post

Link to post
Share on other sites
That's because you need to #include globals.h in terrain.h. If you did so currently, you'd get an infinite loop of includes (since terrain.h has #included itself). Remove those includes from the bottom of your globals.h, and include globals.h in terrain.h.

In addition, the "extern" keyword just tells the compiler to look outside of the current translation unit (the .cpp file) for a certain variable name. For this reason, you can't define a variable with an extern keyword, you can't assign a value to it, because you aren't creating the variable, just telling the compiler to look elsewhere for it. For example:

// foo.cpp
int lol = 100;

int main()
cout << lol;
return 0;

// bar.cpp
extern int lol;
int add()

In foo.cpp, lol is declared as an int and given a value of 100. In bar.cpp, we used the extern keyword to tell the compiler to look outside of bar.cpp for the int variable called "lol". So now both foo.cpp and bar.cpp can see the variable "lol". main() calls add(), which adds 1 to lol. main() then displays the result (which will be 101).

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this