gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:43:49 25 4
gpt4 key购买 nike

我一直想知道是否可以使用带有一些优化标志的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com