Multiple definition - again

Hello, I have seen a post about this issue, but it didn't apply to my problem, so the solution neither.

Development enviroment

gcc/g++ 4.6.3
Ubuntu 12.04
IDE CodeBlock v 10.05

I have the following header file superficies.h

1
2
3
4
5
6
7
8
9
10
11
#ifndef SUPERFICIES_H_INCLUDED
#define SUPERFICIES_H_INCLUDED

#include <SDL.h>

SDL_Surface *screen = NULL;
SDL_Surface *sprite = NULL;

...just more declarations

#endif // SUPERFICIES_H_INCLUDED 


Then I include this header in two files, in one file named Sprites.h and in the main file, main.cpp

Then I have

1
2
3
4
5
6
7
#include "superficie.h"
#include "Sprites.h"

int main()
{
  return 0,
}


I put extern word but it is put by defect, so it doesn't change anything.

I thought it was enough with the header guards to include the variables once, but it seems wasn't.

I have the following messages:

multiple definition of `screen'
obj/Debug/Sprites.o:(.bss+0x38): first defined here

and so on for every variable.

I actually don't have the declaration twice, it seems a linking problem.

I need this variables to be seachable for two or more files, so I put them in that header.

Thanks a lot for any suggestion.

rossig





I thought it was enough with the header guards to include the variables once, but it seems wasn't.
Inclusion guards only protect against including the same header in the same translation unit twice, not against including the same header in two different translation units (if they did, no one would use them).

I actually don't have the declaration twice, it seems a linking problem.
You actually do. Because the line SDL_Surface *screen = NULL; appears in two places (once in Sprites.cpp and once in main.cpp, since both files include the header that contains it), it counts as defining the same symbol twice. What you need to do is move the lines to a single .cpp file that will be used as a normal source, and replace the lines in the header with
1
2
extern SDL_Surface *screen;
extern SDL_Surface *sprite;
thanks a lot helios, after some reading and your post, I could understood and now it works.

Regards

rossig
Last edited on
Topic archived. No new replies allowed.