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"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…