roymcclure
roymcclure

Reputation: 404

Cannot forward declare a typedef?

I am learning C by programming a chess application and I have a problem with circular references. My linkedList.h looks like this:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#ifdef  __cplusplus
extern "C" {
#endif
#ifdef  __cplusplus
}
#endif
#endif  /* LINKEDLIST_H */

#include <stdlib.h>
#include "squares.h"

typedef struct node {
tSquare c;
struct node * next;
} node_square;



void createEmptyList(node_square* n);
int isEmptyList(node_square* n);
int insertAtBeginning(node_square** n, tSquare c); 
void print_list(node_square * head);

And in my squares.h I want to include the linkedList.h functionality so that I can return a linked list of squares threatened by one of the sides (black or white):

#ifndef SQUARES_H
#define SQUARES_H
#ifdef  __cplusplus
extern "C" {
#endif
#ifdef  __cplusplus
}
#endif
#endif  /* SQUARES_H */

typedef struct {
    int file;
    int rank;
} tSquare;

node_square* listOfThreatenedSquares(tColor color); <--- undefined types in compilation time

I've read that what I should use is forward referencing; I am trying to use it so that in the squares.h file I can use types node_square and tColor (which is defined in another file called pieces.h) but no matter how I declare the types, it just isn't working. I guess it's something like

typedef struct node_square node_square; typedef struct tColor tColor;

in the squares.h. Ideas?

Upvotes: 1

Views: 165

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

I guess it's something like

typedef struct node_square node_square;
typedef struct tColor tColor;

This is right - that is indeed a way to forward-declare node_square and tColor. However, forward-declared types are considered incomplete, so you need to follow one rule when using them: you cannot declare variables, arrays, struct members, or function parameters of the forward-declared type itself; only pointers (or pointers to pointers, pointers to pointers to pointers, etc.) are allowed.

This will compile:

node_square* listOfThreatenedSquares(tColor *color);

If you do not wish to use pointers for some reason, you can include the corresponding header to provide the compiler with the actual declaration of the class.

Upvotes: 4

Related Questions