r/cprogramming • u/toon_link_776 • Oct 26 '26
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;
9
u/FancySpaceGoat Oct 26 '26 edited Oct 27 '26
You can use a pointer to a forward-declared struct, but you can't use it as a value type unless you have the actual definition.
Here's an easy way to think about it: How is the compiler supposed to know what
sizeof(objB_t)is supposed to be?sizeof(objA_t*)is easy, it's the same assizeof(void*); the compiler only needs to know thatobjA_texists in order to work with that. Butsizeof(objA_t)doesn't have a value until you know what's inside ofobjA_t.A forward declaration just announces that the name exists and refers to a struct, so it only enables stuff that only needs to know it exists (like pointers).
1
u/girlpuppything Oct 26 '26
afaik C goes thru the code from top to bottom, once. that's why you need to declare a function used in another function before in the code (it's a promise that the defintion will come later). so i'm sure just putting the declaration, where you say which fields it has, of struct obja before struct objb will fix this. idk if there is something equivalent to what can be done with functions.
1
u/SmokeMuch7356 Oct 27 '26
You cannot create instances of incomplete types, but you can create pointers to incomplete types:
When you create a new instance of
objB_t, you will have to create a separate instance ofobjA_tfor theomember to point to:or