Tuesday, October 7, 2008

Preprocessor Warning Signs

Using #if 0 makes searching hard

Some symbol is not defined so you grep for it and you find it in a file. But you've forgotten that you commented that part of the file out. So the symbol exists in the source but not in the .o file, leading to puzzled head-scratching. A better idea is to delete the unwanted lines since you can find them in your version control whenever you want them, and perhaps even leave a message about what they were.

Try this to see how many times you've done this:


[mdoar]$ find . -name \*.[ch] | xargs grep '#if 0' | wc


#ifdefs for unit tests mean that the code tested differs from the code used in the product


If #ifdef has to be used to make a function testable, then perhaps the function needs refactoring? If possible, use the build tool to create the tests, not the preprocessor. Some sample quotes at random from the web:

"I don't ever use ifdefs for unit testing because code should never know it's being unit tested."

"Tests must be non-invasive. I don't want to have to add #ifdef UNIT_TEST declarations into my production codebase as it'll end up making a mess and worse, could actually change behaviours. The framework and test code will be in an externally compiled project"

No comments: