Archived

This topic is now archived and is closed to further replies.

branhield

'multiple definition of variable'-error

Recommended Posts

hey..i get this error ''multiple definition of world'' when i try to compile my project...world is defined in a header and the headers is being used in 2 files main.cpp and display.cpp ''display.cpp - first defined here'' it says this problem occured when i included the header in more than one file

Share this post


Link to post
Share on other sites
At the top of your header write something like this:

#ifndef YOURHEADERFILE_H
#define YOURHEADERFILE_H

And at the end:

#endif


This makes sure the contents of your header file are only defined once.

Share this post


Link to post
Share on other sites
#ifndef GAME_H
#define GAME_H

void GAME_init();
void GAME_display();

BITMAP *ground;
BITMAP *grass;

PALETTE ground_pal;
PALETTE grass_pal;

int world[5][5] = { 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1 };

#endif

Share this post


Link to post
Share on other sites
Of course you get this error. Remember, #include basically makes copies from one file of text into another.

Every file that includes game.h now has the following variables...

BITMAP *ground;
BITMAP *grass;

PALETTE ground_pal;
PALETTE grass_pal;

int world[5][5] = { 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1 };

These variables should be in one .c or .cpp file only.


Why you shouldn''t use iostream.h - ever! | A Good free online C++ book

Share this post


Link to post
Share on other sites
quote:
Original post by branhield
and what if i need to use them in several source files


Use the extern keyword.
See the ''header files'' link in my signature.


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites
I think you should put the variables in main.cpp and use the extern keyword in display.cpp

like this:
main.cpp
--------
BITMAP *ground;
BITMAP *grass;

PALETTE ground_pal;
PALETTE grass_pal;

int world[5][5] = { 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1 };

display.cpp
-----------
extern BITMAP *ground;
extern BITMAP *grass;
extern PALETTE ground_pal;
// etc.

hope that helps

Matt

Share this post


Link to post
Share on other sites