Public Group

This topic is 4270 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Heh, this is driving me nuts. The linker is saying I have multiple definitions of certain variables:
// Resource Variables
StateMachine *state;
BITMAP *ship_img;
BITMAP *bg;
BITMAP *buffer;
BITMAP *alien_img[2];
CShipSprite *ship;
CAlienSprite *aliens[8];

Those are all defined in a game.h file. The rest of it is a class definition and that doesn't get caught in the error. The header file is included once in game.cpp, where the variables are initialized in a function, and once in main.cpp. It also has #pragma once. I can't imagine how any of those variables are being defined multiple times. Any ideas?

Share on other sites
I'm not that familiar with the #pragma once directive (I tend to avoid nonstandard directives, even if they are widely implemented), but my guess is that it includes the header file once per translation unit. If you haven't done so read this article - try putting extern before the variable declarations in the header file and move the definitions to a .cpp file.

Share on other sites
Every time a file is #included, its contents are simply copied as if the contents are part of the file that includes it. Now imagine what would happen if instead of including game.h, you simply paste its contents into every file that includes it. You would get multiple definition errors, right?

Your header file currently contains variable "definitions". A variable definition creates a variable. The solution is to put "extern" at the front of each of those lines in the header file. "extern" makes the line a "declaration". A declaration tells the compiler that the variable exists somewhere, but doesn't "define" it. Now that you have declarations everywhere, you also need to define the variables somewhere (once).

Your code should look something like this:
game.h        extern StateMachine *state; // Declaration. This line tells the compiler                                // that a variable with this name and type                                // exists somewhere.    game.cpp        #include "game.h" // This is always a good idea for many reasons    ...    StateMachine *state; // Definition. Here is where the variable named                         // 'state' resides.        main.cpp        #include "game.h" // Include this so that the declarations tell the                      // compiler about your variables in game.cpp

Share on other sites
Ah I should have known that! Its works pefectly now. Thank you both for the help and the quick response.

1. 1
Rutin
23
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 29
• 40
• 23
• 13
• 13
• Forum Statistics

• Total Topics
631740
• Total Posts
3001959
×