File Organization...

Greetings! I'll try to be short, my problem is this: my code is split between about 6 or so .cpp files, all of them need access to certain variables, but if I declare these variables in all of the locations, the variables have multiple declarations and the compiler returns an error. If I declare the variables only in main.cpp, then the other .cpp files get a compiler error for using an undefined reference. How do you organize multiple .cpp and .h files to get around this dilemma? I could put it all in main.cpp, but it's much easier to stay organized with logical blocks of code separated out. Thanks for your time!

PS- I originally declared all the variables as static in a header file, but this caused references to memory location 0 when I tried to access the static pointers from within instances of objects.
Last edited on
Try to declare all the variables in a header file, using the extern keyword (say "globals.h"):

1
2
3
4
5
6
7
8
// globals.h
#ifndef GLOBALS_H
#define GLOBALS_H

extern <type> <var>;
// ...

#endif // GLOBALS_H 


Include this in all cpp files. In one of the cpp files (e.g. "main.cpp") you initialize all the variables (w/o the extern keyword):

1
2
3
4
5
6
7
8
// main.cpp
#include "globals.h"

<type> <var> = 0;

int main() {
    // ...
}

BTW: In all projects I have worked on (some pretty large ones), I think I have never had to do this. Maybe you could find an easier way to design your code. Hint: Use classes, member variables and function parameters.
The reason I'm having to do it is this: I'm using a static list of pointers to class instances for my collision detection for a game. So for example, I call GetColl, pass it a mode flag to tell it whether the calling object is an enemy, attack or the player, then it uses the list of pointers to access the locations of all the objects it can collide with and checks for collisions. For example, when I right click, the InputHandler function creates a new Attack object and passes it the mouse's x and y coordinates as its destination, but the InputHandler function doesn't store a pointer to the Player object, so it doesn't know where to create the Attack. But the Attack() constructor can access that global pointer to Player and use the get member functions to find the x and y coordinates to initialize itself with. This is also one of my first excursions into OOP, so I'm probably doing this the hard way, but it's the way I've found that works, so I'm going with it.
Topic archived. No new replies allowed.