Reputation: 688
I have a class with a debug function named log(std::string s)
I am working on a small embedded system, therefore I want to remove unnecessary strings from the binary.
I could use #define to achieve what I want, but I think it is a bad practice. Using -Os
optimization I though I could use a const bool
like so:
#include <cstdio>
#include <string>
#include <iostream>
class test
{
const bool enable_debug = false;
void log(std::string s)
{
if (enable_debug) printf("%s",s.c_str());
}
public:
void doStuff(int i)
{
log("I don't want this string to appear in the binary output");
}
};
int main()
{
test instance;
char input;
std::cin>>input;
instance.doStuff(input);
}
Please take a look at the output here: https://godbolt.org/z/qz7csf . As you can see, the string is not removed from the assemby generated code, even though there is no way it can be used, because enable_debug is a const.
#define
?PS : in the end, I would like to have the bool variable external to the class, in order to switch all my classes at the same time.
Upvotes: 1
Views: 297
Reputation: 120059
You are using std::string
. The compiler is not smart enough to see through all the std::string
machinery, and I doubt it is even allowed to eliminate the std::string
construction. Since the string literal is used to initialise the std::string
, the literal cannot be eliminated either.
If you want to save a few bytes, perhaps consider using const char*
instead.
Upvotes: 2
Reputation: 238421
- So why is it still in the output?
Because the compiler didn't do deep enough analysis to find out that it is not used.
- How can I create a toggle switch without using #define?
Put debug functions, including their string literals into a separate translation unit, and don't link with that TU when you don't want them to show.
P.S.
The behaviour is undefined if debugging is enabled:
printf("%s",s);
Upvotes: 0