防止传递不兼容的指针类型

Preventing passing incompatible pointer type

typedef struct A {} A;
typedef struct B {} B;

void doStuff(A* pA) {};

int main() {
   B b;
   doStuff(&b);
}

此代码可以编译(尽管有警告)。有什么办法(编译器选项,或者通过更改 doStuff 的定义)让它不编译吗?

编辑:您可以使用此标志将特定警告视为 GCC/Clang 中的错误:-Werror=<warning name>.

您可以使用 -Werror 标志将警告视为 GCC(或 Clang)中的错误。其他编译器有各自的标志。

然后,你会得到这样的东西:

prog.c: In function 'doStuff':
prog.c:4:17: error: unused parameter 'pA' [-Werror=unused-parameter]
    4 | void doStuff(A* pA) {};
      |              ~~~^~
prog.c: In function 'main':
prog.c:8:12: error: passing argument 1 of 'doStuff' from incompatible pointer type [-Werror=incompatible-pointer-types]
    8 |    doStuff(&b);
      |            ^~
      |            |
      |            B * {aka struct B *}
prog.c:4:17: note: expected 'A *' {aka 'struct A *'} but argument is of type 'B *' {aka 'struct B *'}
    4 | void doStuff(A* pA) {};
      |              ~~~^~
cc1: all warnings being treated as errors

Live Demo