0

Will the string defined by a statement like:

#define CADENA "stringy string\n"

be duplicated in all the .c files where it is being used ? If that is the case then the executable code will grow considerably which is not a good thing. Consider this code:

[niko@dev1 snippets]$ cat str.c
#include <stdio.h>

#define CADENA "stringy string\n"

void printit(char *s) {
    printf("%s",s);
}
void main(void) {
    printit(CADENA);
    printit(CADENA);
}
[niko@dev1 snippets]$ gcc -o str str.c
[niko@dev1 snippets]$ ./str
stringy string
stringy string
[niko@dev1 snippets]$ 

Will the compiler create 2 constant strings in this case or just one ? If it is just a single one then how do you control if the content of the #define directive is copied or a unique reference is made ? Does GCC has any switch or command line option for this?

I checked out what the preprocessor generates, and indeed, the string is duplicated:

[niko@dev1 snippets]$ gcc -E str.c | tail 
# 5 "str.c"
void printit(char *s) {
 printf("%s",s);
}
void main(void) {
 printit("stringy string\n");
 printit("stringy string\n");
}
[niko@dev1 snippets]$ 

In a real use case:

if (some condition) {
    fatal_error(__FILE__,__LINE__,"Can't write to socket");   
}

I am using the constant __FILE__ for debugging purposes, should I better store it in a variable to reduce the code size?

Nulik
  • 6,748
  • 10
  • 60
  • 129
  • Many compilers use "string pooling" in which it discovers you have used that exact string already and uses a pointer to the shared (constant) string. – Paul Ogilvie Sep 05 '16 at 19:54
  • so how do I know if my compiler does or does not use string pooling ? – Nulik Sep 05 '16 at 19:55
  • @PaulOgilvie got it. 'string pooling" are the keywords to search for. We may close this question now. – Nulik Sep 05 '16 at 20:02

0 Answers0