Optimization with GCC

Asked

Viewed 130 times

2

Recently I was wondering if it is possible to compile with some flag optimization, avoid copying two arrays for the section .rodata? Thus, memory addresses would be equal, example

const char str[7] = "string";

const char str1[7] = "string";


int printf(const char *format, ...);

int main(void) {

     if(str == str1) 
         printf("Endereços de memória iguais");

     return 0;

}

So in this example above, is it possible somehow for the compiler to use the same memory addresses?


EDIT:

It doesn’t make much sense anyway no, kkkk, it was just a matter of curiosity anyway, I tried to see some flags optimization, but without success.

#include <stdio.h>

void main(void) {

     char *str1 = "string";
     char *str2 = "string";

     if(str == str2) puts("Igual");
}

In the above example, the compiler places the string pointer literal str1 in the section .rodata and uses the same string, or is the same address for the pointer str2. That’s why I wanted to know if you can simulate this by doing array. I read the Manpage of GCC, but I found nothing relevant in that sense, but anyway thank you very much for your reply.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

Yes, it is possible, although this code doesn’t seem to make much sense:

#include <stdio.h>

int main(void) {
    const char str[7] = "string";
    const char *str1 = str;
    if(str == str1) printf("Endereços de memória iguais");
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I know you expected another answer, but another one doesn’t make sense. In C if you want an optimization, optimize, don’t wait for the compiler to do it for you.

  • 1

    The standard allows two string literals of the same content to have the same storage space and thus the same address. Then I look for a reply (or do it yourself if you want). E.g.: https://godbolt.org/z/qiGPT9

  • To allow is not to guarantee, I prefer the guaranteed.

  • I thought the OP question was about optimizations, something that is not "guaranteed" but "possible."

  • Vlw Mario and Maniero. Achieve using the -fmerge-all-constants flag. In reality the compiler tries to avoid duplicating the strings as long as they are constant and identical, but it is not guaranteed that the compiler will always do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.