c - 使用 ‘-Wcast-qual’ 选项检查编译

标签 c gcc

我正在阅读 an introduction to gcc其中说:

‘-Wcast-qual’ this option warns about pointers that are cast to remove a type qualifier, such as const. For example, the following function discards the const qualifier from its input argument, allowing it to be overwritten:

 void
       f (const char * str)
       {
         char * s = (char *)str;
         s[0] = ’\0’; }

The modification of the original contents of str is a violation of its const property. This option will warn about the improper cast of the variable str which allows the string to be modified.

我试图重复这个,期待一个警告,但是编译时没有警告。我的代码如下:

#include <stdio.h>

void f(const char * str);

int main() {
    char Str = 'a';
    char * myStr;
    myStr = & Str;
    printf ("result: %c \n", * myStr);
    f(myStr);
    printf ("result: %c \n", * myStr);
    return 0;
}


void
f (const char * str)
{
  char * s = (char *)str;
  s[0] = '\0';
}

命令是:gcc -Wcast-qual castqual.c

谁能解释这种不一致?

最佳答案

根据评论,事实证明 OP 使用的是 mac,其中 gcc 作为命令是 clang 的包装器 - 基于 llvm 的编译器。

正在使用的 clang 版本接受该选项但不对其执行任何操作。正在添加对警告的支持,应该出现在 XCode 7/clang 7 时间范围内;然而,问题是关于 gcc 而不是关于 clang

在这种情况下,您需要使用手动或使用软件包管理器(例如 homebrew)安装正确的 gcc 副本。或 macports .安装 gcc 后,它就可用,例如 gcc-4.8gcc-5 等(取决于包管理器)。当你想用实际的 gcc 编译代码时,你使用:gcc-4.8 -Wcast-qual testcode.c。如果您使用的是 autoconf 工具,则可以使用 export CC=gcc-4.8; export CXX=g++-4.8 等,然后该编译器将被包拾取。

验证您正在调用 gcc 而不是 clang 需要检查 gcc --version 的输出。在 clang 包装器上,您会看到类似以下内容:

$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix

而在您看到的实际 gcc 实例上:

$ gcc-5 --version
gcc-5 (Homebrew gcc 5.1.0) 5.1.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

imho aside: you can make a symlink to the specific gcc-4.8 called gcc, and get it to invoke directly like that but it can break other things.

关于c - 使用 ‘-Wcast-qual’ 选项检查编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963233/

相关文章:

c - 二维数组中的值

c - 从传递给函数的结构中写入成员会产生意外结果

c++ - #ifndef FILENAME....#endif 在头文件中的用途

iphone - 将 Apache Portable Runtime 交叉编译到 iPhone

c - C 库的包含路径

c - 城市名称排序失败

创建单独的子函数来计算文件中的每个字母

c - 如何在 gcc 中使用矢量化选项

c++ - 使用 gcc4 优于 gcc34 的好处?

c++ - 构建 GLib 时出错