The structure will not work when it is contained in the header files

advertisements

So I have three concerning files:

MyGame.cpp        //Where all my codeing takes place
MyDirectX.h       //Where I declare prototypes
MyDirectX.cpp     //where I define functions/structs

I have a nice little struct that looks like this:

struct Sprite
{
LPDIRECT3DTEXTURE9 texture;

int frame;
int starttime;

    Sprite()
    {
        texture = NULL;
        texture = LoadTexture("explosion_30_128.tga");
        frame = 0;
        starttime = 0;
    }
};

So Here's the problem:

The struct works just fine when I declare it in MyGame.cpp. However, I need it in my header files because other functions depend on it (and for tidiness sake). I declare it in MyDirectX.h as such:

struct Sprite;

And define it in MyDirectX.cpp:

struct Sprite
{...code...};

I can create a global Sprite in MyGame.cpp

Sprite explosion;

And all checks out. But when I try to explosion.frame = or explosion->frame = (or any other members for that matter) I get the error "Expression must be a pointer to a complete object type."

If I define the entire struct in MyDirectX.h and not MyDirectX.cpp I get an unresolved external symbol. If I define in both I get a redefinition error.

I've been doing tests and researching for hours and I just can't figure this one out. It makes no sense to me why the struct would work in MyGame.cpp but not work when I use it in my header files. I should note that that I've declared and defined many functions in these files and they all work just fine.

Any help would be much appreciated. Thanks.


You need to put the full definition of the struct in a header so it can be accessed by whatever code the complete type:

struct Sprite
{
  LPDIRECT3DTEXTURE9 texture;

  int frame;
  int starttime;

  Sprite();

};

You can then put implementation code in a separate .cpp file. For code that doesn't need the full type, you can continue to use a forward declaration

struct Sprite;