typedef可见性

the*_*man 4 c struct typedef opacity

我有一个".c .h"文件.在头文件(.h)中,我定义了2个typedef结构,让我们称它们为TS1和TS2.

现在,TS1的一个成员的类型是TS2.我希望只有TS1可见.应该隐藏TS2.TS2应仅对".c"文件可见.

我怎样才能做到这一点?

pmg*_*pmg 6

我喜欢使用'-internal'后缀命名私有头文件.以你为榜样,我有

foobar.c
    #include "foobar-internal.h"
    #include "foobar.h"
    /* functions using `struct TS1` and `struct TS2` */
Run Code Online (Sandbox Code Playgroud)

.

foobar.h
    #ifndef H_FOOBAR_INCLUDED
    #define H_FOOBAR_INCLUDED
    struct TS1;
    #endif
Run Code Online (Sandbox Code Playgroud)

.

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
Run Code Online (Sandbox Code Playgroud)

使用您的函数的任何代码,包括更简单"foobar.h",可以使用指针struct TS1.它不能直接使用任何一个struct TS1struct TS2类型的对象.实际上,通过包含just "foobar.h",代码不知道在struct TS2任何地方都存在类型,并且可以根据自己的目的重新定义它.

usercode.c
    #include "foobar.h"
    struct TS1 *x;
    x = newTS1();
    work(x);
    destroyTS1(x);
Run Code Online (Sandbox Code Playgroud)