I have global const char definition in two different files:
f1:
const char foo1[] = "SAME_VALUE";
f2:
const char foo2[] = "SAME_VALUE";
Wanted to understand if in the final binary this will be optimized to take common space in memory. This is in context of GCC
This kind of optimization is called string interning.
GCC sets the
-fmerge-constantsflag by default:Let's make an executable with a 3rd file named f.c to reference the strings:
When you define the following respectively in f1.c and f2.c (proposition#1):
This results in 2 different memory spaces into which the string "SAME_VALUE" is stored. So, the string is duplicated:
But if you define the following respectively in f1.c and f2.c (proposition#2):
You define two pointers which will point on the same string. In this case, "SAME_VALUE" will likely not be duplicated. In the following raw disassembly, the string is at address 2004 and both foo1 and foo2 point to it:
To avoid the duplication with proposition#1, GCC provides
-fmerge-all-constants:Let's rebuild proposition#1 with this flag. We can see that foo2 is optimized out, only foo1 is kept and referenced: