volatile上的gcc unused-but-set-variable警告

ily*_*725 5 c gcc

我有一个小函数,使用volatile变量将值写入HW

void gige_rx_prepare(void) {

    volatile uint hw_write;

    // more code here

    hw_write = 0x32;
}
Run Code Online (Sandbox Code Playgroud)

gcc版本4.7.3(Altera 13.1 Build 162)将此变量标记为已设置但未使用,即使它是易失性的,也便于写入HW寄存器.

我仍然希望在任何其他变量上看到此警告.有没有办法避免在volatile变量上发出此警告,而无需为代码中的每个volatile变量设置gcc属性?

Art*_*emB 6

局部变量不是ah/w寄存器的良好表示,这也是您看到警告的部分原因.

编译器抱怨(正确)因为hw_write是堆栈上的局部变量.在这种情况下,编译器确实有足够的数据来推断它是无意义的赋值.如果它是全局变量或指向易失性uint的指针,则不会发出警告,因为变量生命周期不受函数范围的限制,因此它可能已被用于其他地方.

以下示例编译时没有任何警告:

volatile int hw_write2;  // h/w register
void gige_rx_prepare2(void) {


    // more code here

    hw_write2 = 0x32;
}

void gige_rx_prepare3(void) {
    volatile int *hw_write3 = (void*)0x1234; // pointer to h/w register.


    // more code here

    *hw_write3 = 0x32;
}
Run Code Online (Sandbox Code Playgroud)