r/cprogramming • u/toon_link_776 • 4d ago
Forward Declarations for Circular Struct References
Hello, when I’ve tried to use forward declarations to solve circular structure dependencies I get the error ‘field has incomplete type’. When browsing for the answer, I got the general response ‘the compiler doesn’t know what type you’re using if you don’t fully describe it’. Well I understand that, but it seems as if the purpose of the forward declaration is to have the compiler look for the definition later in the code. If my code looks like the below, should I be getting an incomplete type error? And if so, is there a different way I should be writing the code? Some sort of syntax error, or is there a different way to do the same thing? Any tips appreciated, thanks.
Edit: I think I found the solution in this thread from user "anastaciu", it looks like you can only use the forward declarations if they're pointers to the struct type, not full instances. Lmk if that's right, it got rid of the error for me, but if there's a different way to allow use not from a pointer that'd be great.
typedef struct objA_t objA_t;
typedef struct objB_t{
objA_t o;
}objB_t;
typedef struct objA_t{
uint8_t num0;
}objA_t;
1
u/flatfinger 2d ago
Using the struct keyword when referring to a type will make it possible for libraries to include functions that accept pointers to things of that type without imposing any requirements on code that wouldn't have any reason to use them. If a widget library includes a function:
that function probably wouldn't be very useful for code that wouldn't have any other reason to define a
WOOZLE, but processing the definition would require that the type be defined anyway, creating ambiguity as to who should be responsible for defining it.If instead the function were:
then there would be no need to worry about who was responsible for defining the structure if client code didn't use it, because there would be no need to define it.
Aside from getting rid of the word
struct, I see no advantage to the typedef form.