首页 > 解决方案 > 定义不透明指针时防止不完整的类型声明?

问题描述

C 标准中有一个功能隐藏了我的代码中的错误,我想知道是否有某种方法可以防止它,或者至少发出警告。

在 C 中,此代码隐式声明struct foo为不完整类型:

struct foo *ptr; /* I didn't even tell the compiler I wish to use struct foo */

但是,我宁愿被要求声明不完整的类型,如下所示:

struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */
struct foo *ptr; /* that's fine, pointer to an incomplete type which I said I wish to use */

我正在谈论的错误是我在指针定义中打错了字,因此它指向了一个不完整的类型,该类型是由编译器“动态”创建的,没有任何警告。如果编译器用“指向未声明结构的指针”之类的东西警告我,我会纠正错字。我可以以某种方式启用这样的警告吗?

标签: c

解决方案


只要您不取消引用它或以需要完整类型的方式使用它,指针本身就可以。

如果你尝试你会得到一个错误。

例子:

struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */

void foo(void *vptr)
{
    struct foo *ptr = ptr;
    ptr -> x = 0; //error
}
#include <stdlib.h>
struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */

void foo(void)
{
    struct foo *ptr = malloc(sizeof(*ptr)); // error - incomplete type 
}

https://godbolt.org/z/bnKEGr

由于指向不完整类型的指针是有效的,因此不需要额外的警告消息。


推荐阅读