两者都应带来同样的可使用性,即使通过联系,也应当加以控制?
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).
比较<代码>api.h和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; |
| } |
+---------------------------------+
该信标的客户有两种版本:
#include "api.h"
void good(struct s *foo)
{
api_func(foo, 123);
}
在执行过程中,有一个oke子:
#include "api.h"
void bad(struct s *foo)
{
foo->internal = 123;
}
它将采用“头盔定义”版本,但不采用“执行中的定义”版本,因为在后一种情况下,汇编者对结构的布局不了解:
$ gcc -Wall -c bad.c
bad.c: In function bad :
bad.c:5: error: dereferencing pointer to incomplete type
$
因此,“执行中的定义”版本保护不受意外或蓄意滥用私人执行细节的影响。