小编Iva*_*van的帖子

gcc究竟如何做优化?

为了知道gcc究竟如何进行优化,我编写了两个用-O2编译的程序,但是汇编代码有一些区别.在我的程序中,我想在循环中输出"hello",并在每个输出之间添加一些延迟.这两个程序仅用于说明我的问题,我知道我可以在程序1中使用volatile或asm来实现我的目的.

计划1

#include <stdio.h>

int main(int argc, char **argv)
{
    unsigned long i = 0;
    while (1) {
        if (++i > 0x1fffffffUL) {
            printf("hello\n");
            i = 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用-O2编译,汇编代码是:

Disassembly of section .text.startup:

00000000 <_main>:
#include <stdio.h>

int main(int argc, char **argv)
{
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   83 e4 f0                and    $0xfffffff0,%esp
   6:   83 ec 10                sub    $0x10,%esp
   9:   e8 00 00 00 00          call   e <_main+0xe>
   e:   66 90                   xchg   %ax,%ax …
Run Code Online (Sandbox Code Playgroud)

c optimization gcc compiler-optimization

5
推荐指数
1
解决办法
259
查看次数

不同大小的相同枚举类型

以下代码中枚举类型的大小不同,为什么?枚举类型的声明是否会导致gcc将其视为signed int?此功能会导致我的项目出现问题,例如,"file_1.c"中一个枚举类型的大小为1,但"file_2.c"中的大小为4.

我的测试代码:

enum foo foo_test(void);

enum foo {
    FOO_0
};

enum bar {
    BAR_0
};

int main(int argc, char **argv)
{
    printf("sizeof(enum foo) %d, sizeof(enum bar) %d\n", sizeof(enum foo), sizeof(enum bar));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • 当我在我的嵌入式项目中使用arm-none-eabi-gcc v4.9.3编译它时

    • 输出是sizeof(enum foo) 4, sizeof(enum bar) 1.
  • 当我在Windows中使用gcc v4.8.3编译它时

    • 编译 gcc -Wall -o sizeofTest.exe sizeofTest.c
      • 输出是sizeof(enum foo) 4, sizeof(enum bar) 4.
    • 编译 gcc -Wall -fshort-enums -o sizeofTest.exe sizeofTest.c
      • 输出是sizeof(enum foo) 4, sizeof(enum bar) 1.

c embedded enums

5
推荐指数
1
解决办法
154
查看次数

gcc -O2优化到错误的行为,这是一个错误吗?

我编写了一个非常简单的程序来测试gcc -O2选项,它会产生错误的行为.这是gcc的bug吗?

我的C程序:

#include <stdio.h>

int main(int argc, char **argv)
{
    unsigned long i = 0;
    while (1) {
        if (++i > 0x1fffffffUL) {
            printf("hello\n");
            i = 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我用-O1编译它时,一切都是正确的,我在每个循环中加1.但是当我用-O2编译它时,我被忽略,在每个循环中输出"hello".为什么-O2会导致这种错误行为?是gcc的明显错误吗?我的gcc版本对于cygwin是4.8.3,我尝试了一个新版本,它也有同样的问题.

用-O1编译,汇编代码是:

Disassembly of section .text:

    00000000 <_main>:
    #include <stdio.h>

    int main(int argc, char **argv)
    {
       0:   55                      push   %ebp
       1:   89 e5                   mov    %esp,%ebp
       3:   83 e4 f0                and    $0xfffffff0,%esp
       6:   83 ec 10                sub    $0x10,%esp
       9:   e8 00 00 00 00          call   e <_main+0xe>
       e:   b8 00 …
Run Code Online (Sandbox Code Playgroud)

c optimization gcc

1
推荐指数
2
解决办法
825
查看次数

标签 统计

c ×3

gcc ×2

optimization ×2

compiler-optimization ×1

embedded ×1

enums ×1