How to forward typedef'd struct in .h

erandros picture erandros · Aug 31, 2011 · Viewed 41k times · Source

I have Preprocessor.h

#define MAX_FILES 15

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

typedef struct Preprocessor Prepro;

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}

I realized then that I had to separate declarations from definitions. So I created Preprocessor.c:

#define MAX_FILES 15

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

typedef struct Preprocessor Prepro;

And Preprocessor.h is now:

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}

That obviously, doesn't work because Pr..h doesn't know Prepro type. I already tried several combinations, none of them worked. I can't find the solution.

Answer

Joe picture Joe · Aug 31, 2011

Move the typedef struct Preprocessor Prepro; to the header the file and the definition in the c file along with the Prepro_init definition. This is will forward declare it for you with no issues.

Preprocessor.h

#ifndef _PREPROCESSOR_H_
#define _PREPROCESSOR_H_

#define MAX_FILES 15

typedef struct Preprocessor Prepro;

void Prepro_init(Prepro* p);

#endif

Preprocessor.c

#include "Preprocessor.h"

#include <stdio.h>

struct Preprocessor {
    FILE fileVector[MAX_FILES];
    int currentFile;
};

void Prepro_init(Prepro* p) {
    (*p).currentFile = 0;
}