首页 > 解决方案 > 除了最后一个之外,所有#pragma GCC 诊断都被忽略

问题描述

使用#pragma GCC diagnostic push/pop/warning/ignored...时似乎只有最后#pragma-行生效!为什么?作为示例,我从此处复制并修改了为 gcc 7.3.0 给出的示例

#include <stdio.h>
#include <stdint.h>

static void foo();
static void bar();
static void car();
static void dar();

int main() {

#pragma GCC diagnostic warning "-Wunused-variable"
    foo();         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
    bar();         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    car();         /* error is given for this one */
#pragma GCC diagnostic pop
    dar();         /* depends on command line options */

    return 0;


}

static void foo() {

    volatile uint32_t testArray[UINT8_MAX] = {0};

}

static void bar() {
    volatile uint32_t testArray[UINT8_MAX] = {0};
}

static void car() {
    volatile uint32_t testArray[UINT8_MAX] = {0};
}

static void dar() {
    volatile uint32_t testArray[UINT8_MAX] = {0};
}

用两种方式编译上面的代码

  1. -Wall在命令行中添加

  2. -Wall在命令行中省略

将导致 1. 对所有对 、 和 的调用发出警告foo(),而bar()2.不会​​对任何发出警告 .. 表明最后一个是唯一生效的,并且是遵循命令行规则的那个. 当然,我不是仅通过这个例子得出这个结论,而是我在这里代表的那个。car()dar()#pragma GCC diagnostic pop

关于为什么会这样的任何想法?我做错了吗?

编辑:接受的答案导致以下工作代码:

#include <stdio.h>
#include <stdint.h>

static void foo();
static void bar();
static void car();
static void dar();

int main() {


    foo();         /* error is given for this one */


    bar();         /* no diagnostic for this one */

    car();         /* error is given for this one */

    dar();         /* depends on command line options */

    return 0;


}
#pragma GCC diagnostic warning "-Wunused-variable"
static void foo() {

    volatile uint32_t testArray[UINT8_MAX] = {0};

}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
static void bar() {

    volatile uint32_t testArray[UINT8_MAX] = {0};
}
#pragma GCC diagnostic pop
static void car() {

    volatile uint32_t testArray[UINT8_MAX] = {0};
}
#pragma GCC diagnostic pop
static void dar() {

    volatile uint32_t testArray[UINT8_MAX] = {0};
}

标签: cgccpragma

解决方案


使用最后一个#pragma,因为foobar被放置在您的代码中所有 pragma 行之后。尝试这个:

#pragma GCC diagnostic warning "-Wunused-variable"

static void foo() {
    volatile uint32_t testArray[UINT8_MAX] = {0};
}

pragma影响这一行之后的代码,并且不会像您期望的那样遵循函数调用。


推荐阅读