Issue
I would like to find a way to store duplicate constant strings in a single location. However; I need to get the length of that string at the compiler level (such that it is not found at runtime by functions such as strlen()). I know of a way to do each of these separately, as shown.
Storing duplicate strings in a single address by using pointers:
const char *a = "Hello world.";
const char *b = "Hello world.";
printf("a %s b\n", a == b ? "==" : "!="); // Outputs "a == b" on GCC
Getting the length of a string at compile time:
const char c[] = "Hello world.";
printf("Length of c: %d\n", sizeof(c) - 1); // Outputs 12 on GCC
Though there seems to be no way to combine the two:
const char *d = "Hello world.";
printf("Length of d: %d\n", sizeof(d)); // Outputs the size of the pointer type; 8 on 64-bit computers
const char e[] = "Hello world.";
const char f[] = "Hello world.";
printf("e %s f\n", e == f ? "==" : "!="); // Outputs "e != f" on GCC
const char *g[] = {"Hello world."};
const char *h[] = {"Hello world."};
printf("g %s h\n", g == h ? "==" : "!="); // Outputs "g != h"
printf("Length of g: %d\n", sizeof(g[0])); // Outputs pointer type size
Is there a way to do this that I am unaware of?
Solution
gcc may be able to optimize the strlen() call to get the length at compile time.
Check the -foptimize-strlen
option here https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
Answered By - Archaru Answer Checked By - Marilyn (WPSolving Volunteer)