Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when forward declaring a struct: "has a previous declaration here"

Tags:

c++

When building my small C++ project, I get the following 2 errors, can't figure out the cause:

  • error: using typedef-name 'TTF_Font' after 'struct'.
    Points to the following line of code: struct TTF_Font; in Foo.h.

  • error: 'TTF_Font' has a previous declaration here.
    Points to the following line of code: typedef struct _TTF_Font TTF_Font; in SDL_ttf.h.

I've narrowed it down to the following files in a new test project:

Foo.h:

#ifndef FOO_H
#define FOO_H

struct TTF_Font;

class Foo
{
    TTF_Font* font;
};

#endif // FOO_H

Foo.cpp:

#include "Foo.h"
#include "SDL/SDL_ttf.h"

// No implementation, just testing

Main.cpp:

#include "Foo.h"
int main(int argc, const char* argv[])
{
    Foo a;
    return 0;
}

Do you guys know what I'm doing wrong?

My goal is to forward declare TTF_Font, so I can use it in my header file without including the SDL_ttf header file. I read that including header files in other header files was kinda bad practice, so I switched to forward declarations. All my other forward declarations work fine except this single struct.

When I replace the forward declaration struct TTF_Font; with the header include #include "SDL/SDL.ttf.h", it compiles without errors. So I can use that, but I want to know WHY, dammit :-).

Extra info: I'm using the Code::Blocks IDE with mingw32 compiler. Project uses the SDL graphics library. Not much C++ experience yet, come from C# background.

like image 561
void_Foo Avatar asked Feb 12 '11 10:02

void_Foo


People also ask

Can you forward declare a struct?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

What is a forward declaration in C++?

In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };


1 Answers

You are trying to forward declare something as a different type to what it actually is.

You are declaring:

struct TTF_Font;

when the error message indicates that TTF_Font is actually a typedef, not a struct:

typedef struct _TTF_Font TTF_Font;

The stuct is actually called _TTF_Font.

You can declare the same typedef multiple times so you can just use the typedef declaration instead of the forward declaration to declare the struct and introduce the typedef although it does feel a bit like you are using implementation details of the header that you are trying to defer including.

like image 71
CB Bailey Avatar answered Oct 04 '22 20:10

CB Bailey