是否可以从代码中的#pragma启用格式化字符串诊断,而不是-Wformat命令行选项?

时间:2016-10-23 17:00:17

标签: gcc

这里的#pragma似乎没有任何效果。代码编译时没有任何警告:

#pragma GCC diagnostic warning "-Wformat"

#include <stdio.h>

int main()
{
        int i = 5;
        char s[] = "test";

        /* missing argument */
        printf("%s");
        printf("%d %s", i);
        /* missing format specifier */
        printf("%s", s, i);
        /* type mismatch */
        printf("%d", s);
        printf("%s", i);

        return 0;
}

在命令行上使用-Wformat选项时会出现警告:

[user@host test]$ gcc -c test.c
[user@host test]$ gcc -Wformat -c test.c [A
gcc: [A: No such file or directory
test.c: In function 'main':
test.c:11: warning: too few arguments for format
test.c:12: warning: too few arguments for format
test.c:14: warning: too many arguments for format
test.c:16: warning: format '%d' expects type 'int', but argument 2 has type 'char *'
test.c:17: warning: format '%s' expects type 'char *', but argument 2 has type 'int'

似乎我更改#pragma使其成为错误,然后它在使用-Wformat命令行参数时也只有效果:

#pragma GCC diagnostic error "-Wformat"

然后输出如下:

[user@host test]$ gcc -c test.c
[user@host test]$ gcc -Wformat -c test.c
test.c: In function 'main':
test.c:11: error: too few arguments for format
test.c:12: error: too few arguments for format
test.c:14: warning: too many arguments for format
test.c:16: error: format '%d' expects type 'int', but argument 2 has type 'char *'
test.c:17: error: format '%s' expects type 'char *', but argument 2 has type 'int'

是否有办法启用格式字符串检查,无论是完全来自C代码,还是不需要使用-Wformat命令行参数,都是错误或警告?

我在Linux和AIX之间共享一个简单的Makefile,并且更容易从代码中完成条件编译。

0 个答案:

没有答案