我有一对“.c .h”文件。 在头文件 (.h) 中,我定义了 2 个 typedef struct,我们称它们为 TS1 和 TS2。
现在,TS1 的一个成员的类型是 TS2。 我希望只有 TS1 可见。 TS2 应该被隐藏。 TS2 应该只对“.c”文件可见。
我怎样才能做到这一点?
最佳答案
我喜欢用“-internal”后缀命名私有(private)头文件。对于你的例子,我会
foobar.c
#include "foobar-internal.h"
#include "foobar.h"
/* functions using `struct TS1` and `struct TS2` */
.
foobar.h
#ifndef H_FOOBAR_INCLUDED
#define H_FOOBAR_INCLUDED
struct TS1;
#endif
.
foobar-internal.h
#ifndef H_FOOBAR_INTERNAL_INCLUDED
#define H_FOOBAR_INTERNAL_INCLUDED
struct TS2 { int whatever; };
struct TS1 { int whatever; struct TS2 internal; };
#endif
任何使用您的函数的代码,包括更简单的 "foobar.h"
并且可以使用指向 struct TS1
的指针。它不能直接使用 struct TS1
或 struct TS2
类型的对象。事实上,通过仅包含 “foobar.h”
,代码不知道任何地方都存在 struct TS2
类型,并且可以根据自己的目的重新定义它。
usercode.c
#include "foobar.h"
struct TS1 *x;
x = newTS1();
work(x);
destroyTS1(x);
关于c - typedef 可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677758/