Lets say I have a header file foo.h which declares a struct variable
#include <stdio.h>
typedef struct foo_struct foo_s;
foo_s foo_function(int a);
foo_s bar_function(int b);
and a source file foo.c which actually defines the structure
#include "foo.h"
struct foo_struct
{
int a;
int b;
};
foo_s foo_function(int a)
{
foo_s fs;
fs.a = a;
return fs;
}
Now I want to access the structure defined in foo.c in another source file bar.c so I try the following:
#include "foo.h"
foo_s bar_function(int b)
{
foo_s fb;
fb.b = b;
return fb;
}
…and fail with bar.c:3:7: error: return type is an incomplete type
I sort of understand what the problem is but is there a workaround?
You’re breaking your abstraction by needing to know the definition of
struct foo_structoutside of foo.c. The whole point of making a struct definition “private” to a particular source file is so that other source files aren’t aware of and cannot manipulate the members ofstruct foo_structdirectly.You either need to move
barinto foo.c, or you need to put the struct definition infoo.h(making it public), or you need to define an interface that allows other translation units to allocate, set, read, and deallocate items of typefoo_swithout exposing the details of its type, similar to how the routines instdio.hmanipulate objects of typeFILE, something likeYou would add the above interface to foo.h and implement it in foo.c; functions in other translation units (source files) would use it like:
There are probably a hundred better ways to do that, but you should get the idea.