Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

c - Can GCC merge duplicate global string arrays?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.

Input code:

#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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...