I need to use the constant string "my_string" in 100s of lines in my C code.
And I have constraints on final binary size.
So which one should I go for?
(I am thinking const char* is better because memory allocated to string only once. Am I right...?)
Compiler : gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)
Compiler options: -fPIC -Wall -g -O2 -pthread -O2 -g
If you use
#define CONST_STR "my_string"it will be as if you used "fresh copies" of"my_string"everywhere. Your compiler might consolidate these copies — these days many compilers do as a matter of course — or it might not. There's also the question of whether you'd get copies consolidated across multiple translation units — modern linkers can evidently do this, but I have no idea about yours.If you use
const char *CONST_STR = "my_string";you are guaranteed to have exactly one copy of"my_string". And you can access it in another translation unit (i.e. in another source file) by sayingextern const char *CONST_STR;.Finally, if you use
const char CONST_STR[] = "my_string";you are guaranteed to have exactly one copy of the string, and you'll save a few more bytes by not allocating an extra pointer. You can access it in another translation unit (i.e. in another source file) by sayingextern const char CONST_STR[];.Bottom line: I'd say definitely don't use the
#define. It might waste significant memory, and these days#definetends to be deprecated in favor of const variables anyway.