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

时间:2019-01-10 16:00:38

标签: c compiler-warnings

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

void doStuff(A* pA) {};

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

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

1 个答案:

答案 0 :(得分:3)

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

通过使用-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