Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Forward declaration for struct and function

Tags:

I'm trying to figure out how exactly forward declarations interact. When forward declaring a function that takes a typedef'd struct, is there a way to just get the compiler to accept a previously forward declared (but not actually defined) struct as a parameter?

The code that I've got working:

typedef struct{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

void printCarDeets(automobileType *);

What I wish I could do:

struct automobileType;
void printCarDeets(automobileType *);

//Defining both the struct (with typedef) and the function later

I feel like I'm either missing something really basic or not understanding how the compiler deals with forward declarations of structs.

like image 457
Zac Taylor Avatar asked Oct 09 '16 02:10

Zac Taylor


1 Answers

Typedefs and struct names are in different namespaces. So struct automobileType and automobileType are not the same thing.

You need to give your anonymous struct a tag name in order to do this.

The definition in your .c file:

typedef struct automobileType{
  int year;
  char make[STR_SIZE];
  char model[STR_SIZE];
  char color[STR_SIZE];
  float engineSize;
}automobileType;

The declaration in your header file:

typedef struct automobileType automobileType;
void printCarDeets(automobileType *);
like image 53
dbush Avatar answered Sep 22 '22 16:09

dbush