我有一个抽象的结构:
[trame.h]
typedef struct s_trame t_trame;
// Allocation, setters and getters prototypes
[/trame.h]
[trame.c]
# include "trame.h"
struct s_trame
{
}
// Allocation, setters and getters implementations
[/trame.c]
在另一个文件中,我需要了解t_trame中的字段。我发现这样做的唯一方法是包括trame.c文件。在这种特定情况下情况有多糟?如何做得更好?
[main.c]
# include "trame.h"
# include "trame.c"
int main()
{
t_trame trame;
// Do something with trame
return 0;
}
[/main.c]
我并不想破坏抽象,但是我更喜欢在某些实现中使用该结构。
最佳答案
这是在C中对结构进行黑盒处理的一种非常常见的方法。但是,要使结构真正不透明,您应该在函数中包装对结构的所有访问,包括创建和销毁。
喜欢
t_trame *trame_create(); /* Allocates and initializes the structure */
void trame_destroy(t_trame *); /* Frees the structure */
void trame_do_something(t_trame *, int some_argument); /* Does something with the structure */
int trame_get_some_data(t_trame *); /* Returns some data from the structure */
等等
这样,使用该结构的任何代码都无需查看实际结构,它仅具有指向该结构的指针,并且无需调用您的函数即可对该结构进行任何操作。
关于c++ - C ADT:* .c文件包含,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24956903/