Reputation: 4708
I'm writing a C program that uses a custom logging function to debug my program. Whenever I compile my program as a release version, I want all of my logging functions to be stripped from the code so it won't show up if someone tries to disassemble it.
Take the following example:
#include <stdio.h>
void custom_logging_function(char* message)
{
// Do something here
}
int main()
{
custom_logging_function("Hello world"); // This call should be removed.
return 0;
}
How could I make it so that the custom_logging_function
and it's arguments aren't compiled into my program without having to write include guards everywhere throughout my code? Thank you
Upvotes: 2
Views: 99
Reputation:
You can use pre-processor flags, for example:
#include <stdio.h>
#ifdef DEBUG
void custom_logging_function(char* message)
{
// Do something here
}
#else
#define custom_logging_function(x) ((void) 0)
#endif
int main()
{
custom_logging_function("Hello world"); // This call should be removed.
return 0;
}
With this code you will have to tell the "debug" target to define DEBUG
, if you want to define something specifically for the "release" target you can replace #ifdef DEBUG
with #ifndef NDEBUG
and add the NDEBUG
flag to the "release" definitions.
Edit:
Changed #define custom_logging_function(x) 0
to #define custom_logging_function(x) ((void) 0)
inspired by @JoachimPileborg his answer.
Upvotes: 6
Reputation: 409136
Assuming you only want the logging calls to happen in a debug-build of your application, and not the release build you send to customers, you can still use the preprocessor and conditional compilation for it. It can be made vert simple though by using macros instead of having checks at every call.
Something like this in a heder file:
#ifdef _DEBUG
void custom_logging_function(char* message);
#else
# define custom_logging_function(message) ((void) 0)
#endif
You could use an empty macro body for the release-macro, but that can cause some compilers to give "empty statement" warnings. Instead I use an expression casted to void
(to tell the compiler that the result of the expression will not be used). Any smart compiler will not include the expression after optimization.
Upvotes: 2