首页 > 解决方案 > 在 C 文件中重新声明不透明结构

问题描述

我正在处理一个头文件,该文件声明了一些 opaquestruct应该在相应的 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_tlibrary_struct. 我试过这个:

decl.c

//...
typedef library_struct test; //error: conflicting types for ‘test’
//...

但它不编译。所以我现在能看到的唯一方法是

struct test_t{
    library_struct *lib_struct_ptr;
};

有没有更短或更方便的方法?两者都是不透明的testlibrary_struct为什么我不能使test与 相同library_struct?宏在这里有用吗?

标签: cstruct

解决方案


你的代码相当于

typedef struct test_t test; /* from decl.h */
typedef library_struct test; /* in decl.c */

所以你重新定义测试,当然编译器不接受

我不知道您希望通过宏做什么,但不允许重新定义。

在最坏的情况下,您可以使用void *then 转换为您(希望)拥有的类型来隐藏指针的类型,但这显然是危险的,因为编译器会跟随您,风险自负

编译器不会针对您检查类型,而是帮助您在编译时查看错误...


推荐阅读