c - typedef 可见性

标签 c struct typedef opacity

我有一对“.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 TS1struct 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/

相关文章:

c++ - 从 C 程序调用的 C++ 库中的新建和删除

c - XOR 链表 XOR 函数

c - 从 struct 分配给类型 struct * 时不兼容的类型

c - 有没有办法 extern typedef 变量

c++ - 没有匹配的函数用于调用c++

c - 任意数量数字的平均值

c - 使用函数指针、结构、 union 和枚举进行子类型化

c# - 静态成员导致结构布局中的循环

c - 使用 .h 文件中声明的 C 类型

c - 在命令提示符中监视 Netbeans C/C++ 的输出