我已经struct
在头文件和声明中看到了s的完整定义- 一种方法对另一种方法有什么优势吗?
如果它有所不同,我通常会在这里输入一个这样的结构 .h
typedef struct s s_t;
Run Code Online (Sandbox Code Playgroud)
需要明确的是,选项是头文件中的声明和类中的定义,或者头文件中的声明和定义.两者都应该产生相同的可用性,即使一个是通过联系,不应该吗?
我看到很多几乎重复,例如这里但没有完全匹配.如果我在这方面错了,请纠正我.
τεκ*_*τεκ 98
该文件的私有结构应该放在.c文件中,如果它们被.h中的任何函数使用,则在.h文件中有声明.
公共结构应该放在.h文件中.
Mat*_*ery 67
两者都应该产生相同的可用性,即使一个是通过联系,不应该吗?
不,当你考虑包括相同标题的其他.c文件时.如果编译器看不到结构的定义,则不能使用该定义的详细信息.没有定义的声明(例如just struct s;
)会导致编译器失败,如果有任何东西试图查看内部struct s
,同时仍然允许它进行例如编译struct s *foo;
(只要foo
以后不被解除引用).
比较以下版本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; |
| } |
+---------------------------------+
Run Code Online (Sandbox Code Playgroud)
API的此客户端适用于以下任一版本:
#include "api.h"
void good(struct s *foo)
{
api_func(foo, 123);
}
Run Code Online (Sandbox Code Playgroud)
这个在实现细节中探讨:
#include "api.h"
void bad(struct s *foo)
{
foo->internal = 123;
}
Run Code Online (Sandbox Code Playgroud)
它将使用"头文件中的定义"版本,但不适用于"实现中的定义"版本,因为在后一种情况下,编译器无法看到结构的布局:
$ gcc -Wall -c bad.c
bad.c: In function 'bad':
bad.c:5: error: dereferencing pointer to incomplete type
$
Run Code Online (Sandbox Code Playgroud)
因此,"实现中的定义"版本可防止意外或故意滥用私有实现细节.
归档时间: |
|
查看次数: |
82540 次 |
最近记录: |