GCC 可以合并重复的全局字符串数组吗?

标签 c gcc compiler-optimization

我一直想知道是否可以使用带有一些优化标志的 GCC 进行编译,以避免 .rodata 部分有两个重复的数组?因此,内存地址将是相同的。例如:

const char str [7] = "string";

const char str1 [7] = "string";


int printf (const char * format, ...);

int main (void) {

      if (str == str1)
          printf ("Equal memory addresses");

      return 0;

}

那么在上面的例子中,编译器是否有可能以某种方式使用相同的内存地址?

最佳答案

GCC 的 -fmerge-all-constants (这也意味着 -fmerge-constants)可以解决这个问题。 It's documentation :

-fmerge-all-constants

Attempt to merge identical constants and identical variables.

This option implies -fmerge-constants. In addition to -fmerge-constants this considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. Languages like C or C++ require each variable, including multiple instances of the same variable in recursive calls, to have distinct locations, so using this option results in non-conforming behavior.

请注意,GCC 不保证常量将被合并,因此您不应依赖于此来实现程序行为。它将尝试合并它可以合并的内容,但某些常量可能无法合并。

输入代码:

#include <stdio.h>

const char str1[7] = "string";
const char str2[7] = "string";

int main() {
    puts(str1);
    puts(str2);
}

Output assembly:

main:
        sub     rsp, 8
        mov     edi, OFFSET FLAT:str1
        call    puts
        mov     edi, OFFSET FLAT:_ZL4str2
        call    puts
        xor     eax, eax
        add     rsp, 8
        ret
str1:
        .string "string"

关于GCC 可以合并重复的全局字符串数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077119/

相关文章:

c++ - char * arr[5] = {...} 上的访问冲突,这是什么?

c++ - g++: 错误: 无法识别的命令行选项 '-mt'

c++ - 使用 `size_t` 长度会影响编译器优化吗?

c - GCC SSE代码优化

C winsock2.h WS2_32.lib 链接 undefined reference

c - 在 C 中实现定点数的麻烦

c - 如何使用管道在线程之间发送数组?

c - 以编程方式执行递归 ping shell 命令

c - Yocto 构建 - loadlocale.c#130

c++ - 为什么优化标志 (-O3) 不能加速四倍精度计算?