【问题标题】:c gcc compiler options for pointer arithmetic warningc gcc 用于指针算术警告的编译器选项
【发布时间】:2010-01-04 06:06:36
【问题描述】:

我正在使用以下标志,但我仍然无法收到此警告:

算术中使用的void * 类型指针

使用的标志:

-O2 -Werror -Wall -Wno-main -Wno-format-zero-length -Wpointer-arith -Wmissing-prototypes -Wstrict-prototypes -Wswitch -Wshadow -Wcast-qual -Wwrite-strings -Wno-sign-compare -Wno-pointer-sign -Wno-attributes  -fno-strict-aliasing     

-Wpointer-arith 应该会收到此类警告,但我无法收到此警告:

算术中使用的void * 类型指针

应该使用哪个特定的 cflag 来获得此警告?

编辑:我的错误,它是作为未定义的宏检查的一部分。 :( 通过定义那个宏,我可以得到那个错误。

【问题讨论】:

  • 你使用的是哪个版本的 gcc?
  • 能否提供源代码。只需改进源代码,您就可以清除警告。
  • 对不起..它基本上是netbsd的一部分..我不能发布程序。 gcc 版本:arm--netbsdelf-gcc -v 使用内置规范。目标:arm--netbsdelf 线程模型:posix gcc version 4.1.2 20061021 (prerelease) (NetBSD nb3 20061125)
  • 您能否发布一个minimal 代码示例来展示您所看到的内容?当您在我的答案中编译程序时会发生什么?
  • 还有一个和你有同样问题的小代码呢。只是把假变量名,假函数名等),所以它不会被识别。

标签: c gcc compiler-construction


【解决方案1】:

你是对的。 -Wpointer-arith 应该按照documentation 给你一个警告。

我刚刚尝试了以下程序(故意错误):

~/code/samples$ cat foo.c
#include <stdio.h>
int main (int argc, char **argv)
{
  void * bar;
  void * foo;
  foo = bar + 1;
  return 0;
}

我只使用-Wpointer-arith 选项以及上面列出的所有选项来编译程序。两次尝试都引发了预期的警告。我正在使用 gcc 版本 4.3.4 (Debian 4.3.4-6)。:

~/code/samples$ gcc -Wpointer-arith foo.c
foo.c: In function ‘main’:
foo.c:6: warning: pointer of type ‘void *’ used in arithmetic

~/code/samples$ gcc -O2 -Werror -Wall -Wno-main -Wno-format-zero-length -Wpointer-arith -Wmissing-prototypes -Wstrict-prototypes -Wswitch -Wshadow -Wcast-qual -Wwrite-strings -Wno-sign-compare -Wno-pointer-sign -Wno-attributes -fno-strict-aliasing foo.c
cc1: warnings being treated as errors
foo.c: In function ‘main’:
foo.c:6: error: pointer of type ‘void *’ used in arithmetic

如果你给它“正确”的代码,编译器会抛出警告。因此,我建议您检查为什么这是您预期的警告。可能你编译的代码变了?

我可以给你一个可能的线索:上面代码中的foo = bar + 1; 会触发警告。但是foo = bar ++; 不会(您会收到不同的警告)。因此,如果您的代码在指针上使用递增(或递减)运算符,它可能不会触发警告。

我知道这不是一个直接的答案,但我希望这可以帮助您集中精力进行调查。

【讨论】:

  • 我们真正想要的是警告使用“+”的任何指针算法。我误读了这篇文章,并认为我找到了答案。但是指针运算是 C 的灵魂的一部分。当然 cerr
【解决方案2】:

在 OS X 上使用 gcc 4.2.1,我收到以下警告:

p.c:7: warning: wrong type argument to increment

对于以下程序:

#include <stdio.h>

int main(void)
{
    int i[] = { 42 };
    void *p = i;
    printf("%p\n", p++);
    return 0;
}

我将其编译为:

$ gcc -Wpointer-arith p.c

你能发布你的程序,或者发布上面的编译结果吗?

【讨论】:

  • 对不起..它基本上是netbsd的一部分..我不能发布程序。 gcc 版本:arm--netbsdelf-gcc -v 使用内置规范。目标:arm--netbsdelf 线程模型:posix gcc version 4.1.2 20061021 (prerelease) (NetBSD nb3 20061125)
  • 我的错误,它作为未定义的宏检查的一部分存在。 :(
猜你喜欢
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2011-08-31
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多