2011-04-15 31 views
4

我有一个“.c .h”夫妇。 在.h中定义了2个typedef结构,比如说TS1和TS2typedef知名度

现在,TS1的一个成员是TS2类型。 我想只使TS1可见,但不能TS2。 TS2应该只对相对.c文件可见。

我该怎么做?

+0

成员声明为指针或结构? – tia 2011-04-15 14:04:59

回答

5

我喜欢用'-internal'后缀命名专用头文件。对于你的例子,我会有

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",代码不知道在任何地方都存在类型,并且可以将其重新定义为自己的目的。

usercode.c 
    #include "foobar.h" 
    struct TS1 *x; 
    x = newTS1(); 
    work(x); 
    destroyTS1(x); 
+0

请注意'私人'不是C中的关键字。 – fnokke 2011-04-15 14:29:52

+0

@fnokke:谢谢。我将标识符更改为内部以避免混淆。 – pmg 2011-04-15 14:42:53

+0

但是,当foobar-internal.h'永远不会被包含在任何地方时,编译器如何知道'TS1'和'TS2'的定义? – 2012-06-25 15:10:24

0

AFAIK,这是不可能的。但是您可以为TS1和TS2设置两个不同的.h文件。

2

我同意Rumple。

你可以做的是#define TS2 int在.h和#undef TS2位于.c文件顶部的#include之后。

虽然这不使用typedef。如果你想在多个.c文件中使用#include,你也可以在.h文件的底部输入#undef