Home > other >  Should I `#ifdef DEBUG` guard debugging functions in .c files?
Should I `#ifdef DEBUG` guard debugging functions in .c files?

Time:11-20

Right now I have a debugging function, printPassport, in myfile.h file. It's declared as so:

#ifdef DEBUG
void printPassport(passport_t *passport);
#endif

This seems to be the proper way to do things, though it's been a while since I've used C so please correct me if I'm wrong.

Should I put guards around the function name in myfile.c? i.e. should I do

void printPassport(passport_t *passport) {
...
}

or

#ifdef DEBUG
void printPassport(passport_t *passport) {
...
}
#endif

in myfile.c?

CodePudding user response:

If you guard the function, then it won't be compiled when you don't define DEBUG, which means the code will get out of sync with the rest of the system. Then, when you do need the debugging code, you first have to fix it before you can use it.

It is better in many respects to leave the function being compiled most of the time so that it is known to be valid. Since you have the definition in a header, simply leave the function defined (and compiled) for normal builds. You might use a conditional such as #ifndef RELEASE_BUILD to squeeze the unused function out of the final released product. But the key is to ensure that the function is normally compiled, even if not normally used. You also need to consider how the calls to the function are protected. Is there a runtime debugging level to activate the debugging, or is it strictly a compile-time decision. If it is decided at compile time, you will need suitable guards around the function calls, or a macroized call to the function that can be converted to ((void)0) or something similar by the compiler.

If the function is static — local to one source file, then consider making it static inline. This will be compiled, but will be ignored if it is never called without triggering complaints about unused static functions, even if there are no actual calls to the function.

CodePudding user response:

The NDEBUG macro controls the assert macro; it may be useful to reuse it instead of having another macro.

Whether you want the function to exist, depends on the goal. If you don't need it, you can save compile time, and make the program more consistent by guarding it in .cpp and not having it.

  • Related