GCC可以合并重复的全局字符串数组吗? [英] Can GCC merge duplicate global string arrays?

查看:138
本文介绍了GCC可以合并重复的全局字符串数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been wondering if it's possible to compile using GCC with some optimization flag to avoid have two duplicate arrays to the .rodata section? Thus, memory addresses would be the same. For example:

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;

}

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

So in this example above, is it possible that somehow the compiler uses the same memory addresses?

推荐答案

GCC的-fmerge-all-constants(这也意味着-fmerge-constants)可以解决问题. 它是文档:

GCC's -fmerge-all-constants (which also implies -fmerge-constants) will do the trick. It's documentation:

-fmerge-all-constants

试图合并相同的常量和相同的变量.

Attempt to merge identical constants and identical variables.

此选项暗含-fmerge-constants.除了-fmerge-constants之外,例如甚至常量初始化数组或带有整数或浮点类型的初始化常量变量.诸如C或C ++之类的语言要求每个变量(包括递归调用中同一变量的多个实例)具有不同的位置,因此使用此选项会导致行为不一致.

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不保证常量将被合并,因此您不应依赖于此来实现程序行为.它将尝试合并它可以的内容,但是某些常量可能不可合并.

Note that GCC does not guarantee the constants will be merged, so you shouldn't rely on this for program behavior. It will attempt to merge what it can, but some constants may not be mergeable.

输入代码:

#include <stdio.h>

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

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

> 输出程序集:

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可以合并重复的全局字符串数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆