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
CodePudding user response:
This isn't really an answer but...
I don't think that you should worry about this at all. The compiler is much smarter than we are and will do the best thing. You're going to waste a lot of your time trying to optimize string literals.
Just code in a way that makes sense to you.
However, it's worth noting that if you're trying to optimize for size you might want to use the -Os option instead of -O2
-Os Optimize for size. -Os enables all -O2 optimizations except those that often increase code size:
-falign-functions -falign-jumps -falign-labels -falign-loops -fprefetch-loop-arrays -freorder-blocks-algorithm=stc It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size.
CodePudding user response:
With the right compiler optimisation settings you won't see any difference in the amount of memory used.
One point that is consistently missed though is that the use of const
variables rather than #defines
greatly improves the ease of locating coding errors related to them.
In fact the compiler itself will aid you in preventing the introduction of bugs, as it will also perform type checking during compilation on the use of a const
variables, whereas they invariably don't on #define
.
That is not to say that there isn't a place for #define
just that they shouldn't always be your first port of call.
CodePudding user response:
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 saying extern 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 saying extern const char CONST_STR[];
.
Bottom line: I'd say definitely don't use the #define
. It might waste significant memory, and these days #define
tends to be deprecated in favor of const variables anyway.