Reputation: 604
I have a header file that declares an ADT modeling a tuple. The header contains a declaration of the struct as typedef struct Tuple * Tuple;
The corresponding implementation file defines this as
struct Tuple
{
int x;
int y;
int z;
int w;
};
The problem is that I want to import just the header file in client code (such as a test file or a file containing main). I don't want to include the .c implementation file. Not doing so however results in an error message when attempting code from client code such as:
Tuple tuple = ( Tuple ) calloc( 1, THREE_TUPLE_COORDINATES * sizeof( Tuple ) );
tuple->x ;
that reads as follows: error: dereferencing pointer to incomplete type ‘struct Tuple’
Is it possible leave leave the struct incomplete/undefined in the header and then define it in the implementation file or is this not done/not best practice?
Upvotes: 1
Views: 81
Reputation: 181036
error: dereferencing pointer to incomplete type ‘struct Tuple’
Is it possible leave leave the struct incomplete/undefined in the header and then define it in the implementation file or is this not done/not best practice?
You cannot use an abstract / incomplete data type in any context where the actual definition matters. Such contexts include declaring instances, accessing members, and determining the size. How is the compiler supposed to know how much space to reserve? Or where within that space to find the member with a particular name? Or whether such a member even exists?
You can provide functions for most of those things in the same translation unit(s) where the type is defined, and then let other translation units rely on those functions. All instances obtained that way will need to be dynamically allocated, and all member accesses will incur the cost of a function call. This sort of thing is sometimes done, but it's also often not done. Do think carefully about what you want to gain by doing it.
Upvotes: 2