I wanted to ask about Forward Declarations in C. How generally they work.
For example if in a file I declare
struct task_struct;
and define the struct in other file will it work? Because as far as I know Compiler must know the size of variable that is being declared. If it does then how does compiler actually handles such type of requests?
I found the above example in Linux Source code that got me interested.
Once you use a forward declaration, the type becomes Incomplete type for the compiler.
Compiler does not know anything about the size or layout of the type and hence you cannot perform any operation which needs the compiler to know these.
In C, If you forward declare a type, you can only use a pointer to that type. Since pointers to all structure types need same size[Note], the compiler is just happy to know that it has a pointer to a type.
It will as long as you only use a pointer to the structure in the file which forward declares the structure. If you dereference the pointer you will get errors, Since compiler is not aware of the layout of the Incomplete type.
[Note] Thanks to melpomene & Daniel for this clarification.