Paradoxis Paradoxis - 3 months ago 14
C Question

Stripping specific functions on compile time

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

Answer

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.

Comments