在C文件中重新说明不透明结构
我正在处理一个头文件,它声明了一些不透明的在C文件中重新说明不透明结构,c,struct,C,Struct,我正在处理一个头文件,它声明了一些不透明的structs,应该在相应的C文件中定义。这是: decl.h #ifndef DECL_H #define DECL_H typedef struct test_t test; #endif // 应该在实现中使用的某些库在其头文件lib.h中定义了另一个不透明结构: //... typedef struct _library_struct_t library_struct; //... 现在在我的decl.c文件中,我想使struct tes
struct
s,应该在相应的C文件中定义。这是:
decl.h
#ifndef DECL_H
#define DECL_H
typedef struct test_t test;
#endif //
应该在实现中使用的某些库在其头文件lib.h
中定义了另一个不透明结构:
//...
typedef struct _library_struct_t library_struct;
//...
现在在我的decl.c
文件中,我想使struct test\t
与library\u struct
相同(或兼容)。我试过这个:
decl.c
//...
typedef library_struct test; //error: conflicting types for ‘test’
//...
但它不编译。所以我现在能看到的唯一出路就是
struct test_t{
library_struct *lib_struct_ptr;
};
有更短或更方便的方法吗?
test
和library\u-struct
都是不透明的。为什么我不能使测试
与库结构
相同?宏在这里有用吗?您的代码相当于
typedef struct test_t test; /* from decl.h */
typedef library_struct test; /* in decl.c */
所以你重新定义了测试,当然编译器不接受
我不知道你希望通过宏做什么,但不允许重新定义
在最坏的情况下,您可以使用void*
隐藏指针的类型,然后将其转换为您(希望)拥有的类型,但这显然是危险的,因为编译器将跟随您,风险自负
编译器不会针对您检查类型,而是帮助您在编译时查看错误…“我想使A与B相同”为什么?@alk在C文件中,我计划使用运行在
库结构上的库函数。因此,每次从struct test\t
中提取library\u struct*
都有助于避免这种样板文件。您创建了一个新的用户定义类型library\u struct
,然后创建了test
,这是一个新的用户定义类型,属于library\u struct
;所以本质上你是从一个类型创建了一个类型。我不太清楚您为什么要这样做?为什么不typedef library\u struct test代码>?标题的用户仍然可以只使用test
;实际上它是struct\u library\u struct\t
只是幕后的一个细节。@aschepler因为库是特定于平台的,所以不同的库将用于不同的平台。我同意。这是不可能的,因为typedef
name引用了不同的类型<代码>6.7(p3)
:可以重新定义typedef名称,以表示与当前相同的类型,前提是该类型不是可变修改的类型