c - 为什么 gcc 使用 -O0 进行一些优化

标签 c linux gcc optimization

我使用 gcc 4.8.4 和 -O0 标志编译了以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

static jmp_buf env;

static void
doJump(int nvar, int rvar, int vvar)
{
    printf("Inside doJump(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
    longjmp(env, 1);
}

int
main(int argc, char *argv[])
{
    int nvar;
    register int rvar;          
    volatile int vvar;         

    nvar = 111;
    rvar = 222;
    vvar = 333;

    if (setjmp(env) == 0) {     
        nvar = 777;
        rvar = 888;
        vvar = 999;
        doJump(nvar, rvar, vvar);
    } else {                    
        printf("After longjmp(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
    }

    exit(EXIT_SUCCESS);
}

它产生了以下输出:

Inside doJump(): nvar=777 rvar=888 vvar=999
After longjmp(): nvar=777 rvar=222 vvar=999

我的预期是 rvar 将在第二行中为 888,因为所有优化都已禁用。

当我从 'rvar' 的定义中删除 'register' 或当我在 'register' 前面添加 'volatile' 时,它输出 888。

因此尽管有 -O0 标志,gcc 似乎仍然执行一些优化。

有没有办法完全禁用 gcc 中的所有优化?

最佳答案

C11 标准对 longjmp() 说:

All accessible objects have values, and all other components of the abstract machine249) have state, as of the time the longjmp function was called, except that the values of objects of automatic storage duration that are local to the function containing the invocation of the corresponding setjmp macro that do not have volatile-qualified type and have been changed between the setjmp invocation and longjmp call are indeterminate.

249) This includes, but is not limited to, the floating-point status flags and the state of open files.

您遇到了不确定的值...符合标准的行为。

关于c - 为什么 gcc 使用 -O0 进行一些优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906896/

相关文章:

c - 如何使用NDK为Android设备(ARM)编译C代码?

linux - 从 Linux shell 发送邮件的格式不正确

ubuntu - 编译 ://lib/x86_64-linux-gnu/libm. so.6:添加符号时出错:缺少 DSO

linux - 检查 g++ 的返回值

c - 使用 snprintf() 填充 char 数组

c - 如何在 C 中将 int 转换为字符串 (char*)

C:获取两个字符串之间包含空格的字符串

mysql - 在 DMZ 后面的数据库上运行 SQL 查询

windows - 如何在 Windows 上构建 GCC 4.7?

c - 如何使用宏进行 undefined reference