#pragma GCC diagnostic error "-Wformat"的使用

在GCC下,#pragma GCC diagnostic error用于表示将诊断视为错误。

格式:

#pragma GCC diagnostic error "-Wformat"

示例程序如下:

#include <stdio.h>

/************************************************************************/
int test1(void)
{
    return;
}

//将"-Wreturn-type"诊断视为错误
#pragma GCC diagnostic error "-Wreturn-type"

int test2(void)
{
    return;
}

/************************************************************************/
int main(int argc, char* argv[])
{
    test1();
    test2();
    
    return 0;
}

在gcc下编译

gcc -o test test.c -Wall

函数test1会提示警告不带返回值,而函数test2会提示错误不带返回值。

test.c: 在函数‘test1’中:
test.c:8:5: 警告: 在有返回值的的函数中,‘return’不带返回值 [-Wreturn-type]
test.c: 在函数‘test2’中:
test.c:16:5: 错误: 在有返回值的的函数中,‘return’不带返回值 [-Werror=return-type]
cc1: some warnings being treated as errors

如果屏蔽掉

//#pragma GCC diagnostic error "-Wreturn-type"

重新编译,则两个函数都是提示警告

test.c: 在函数‘test1’中:
test.c:6:5: 警告: 在有返回值的的函数中,‘return’不带返回值 [-Wreturn-type]
test.c: 在函数‘test2’中:
test.c:14:5: 警告: 在有返回值的的函数中,‘return’不带返回值 [-Wreturn-type]

[参考资料]
GCC, the GNU Compiler Collection
GCC, Diagnostic Pragmas

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐