# 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;
extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC) wglGetProcAddress("glMultiTexCoord2fARB");
extern PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB");
extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC) wglGetProcAddress("glClientActiveTextureARB");

#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 on other sites
You should give a value to the global variable in one translation unit only (ergo, in a *.cpp file).

##### Share on other sites
:( it seems that terrain.h doesn't see these variables anyway

##### 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.cppint lol = 100;int main(){   add();   cout << lol;   return 0;}// bar.cppextern int lol;int add(){    lol++;}

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 on other sites
So that's how extern works, something like forward definition. I declared types of that variables in cpp file where I set them and...

IT WORKS!

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627694
• Total Posts
2978673

• 19
• 14
• 12
• 10
• 12