undefined C struct forward declaration

ant2009 picture ant2009 · Mar 7, 2009 · Viewed 39.8k times · Source

I have a header file port.h, port.c, and my main.c

I get the following error: 'ports' uses undefined struct 'port_t'

I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.

I need to have the forward declaration as I want to hide some data in my port.c file.

In my port.h I have the following:

/* port.h */
struct port_t;

port.c:

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};

main.c:

/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}

Many thanks for any suggestions,

Answer

Matthew picture Matthew · Mar 7, 2009

Unfortunately, the compiler needs to know the size of port_t (in bytes) while compiling main.c, so you need the full type definition in the header file.