Thursday, 3 May 2018

header - Should struct definitions go in .h or .c file?


Both should result in the same usability, even if one is by linkage, shouldn't they?



No, not when you consider other .c files including the same header. If the definition of the structure is not visible to the compiler, the details of that definition cannot be used. A declaration without a definition (e.g. just struct s;) causes the compiler to fail if anything tries to look inside struct s, while still allowing it to e.g. compile struct s *foo; (as long as foo is not later dereferenced).


Compare these versions of api.h and api.c:


Definition in header:                 Definition in implementation:
+---------------------------------+ +---------------------------------+
| struct s { | | struct s; |
| int internal; | | |
| int other_stuff; | | extern void |
| }; | | api_func(struct s *foo, int x); |
| | +---------------------------------+
| extern void | +---------------------------------+
| api_func(struct s *foo, int x); | | #include "api.h" |
+---------------------------------+ | |
+---------------------------------+ | struct s { |
| #include "api.h" | | int internal; |
| | | int other_stuff; |
| void | | }; |
| api_func(struct s *foo, int x) | | |
| { | | void |
| foo->internal = x; | | api_func(struct s *foo, int x) |
| } | | { |
+---------------------------------+ | foo->internal = x; |
| } |
+---------------------------------+

This client of the API works with either version:


#include "api.h"
void good(struct s *foo)
{
api_func(foo, 123);
}

This one pokes around in the implementation details:


#include "api.h"
void bad(struct s *foo)
{
foo->internal = 123;
}

which will work with the "definition in header" version, but not with the "definition in implementation" version, as in the latter case the compiler has no visibility of the layout of the structure:


$ gcc -Wall -c bad.c
bad.c: In function 'bad':
bad.c:5: error: dereferencing pointer to incomplete type
$

So, the "definition in implementation" version protects against accidental or deliberate misuse of private implementation details.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...