Using the C Preprocessor in web application development
January 2nd, 2009I use a lot of existing tools for managing and building my software projects. One of those is the C preprocessor (CPP). It’s been around for years, is available on pretty much every flavor of UNIX/Linux including Mac OS X (with XCode installed), and allows me to write code with logging and tests in-line with the ability to have that code stripped out in my build process by simply using a single setting. In Javascript for example, I might have some code like this:
function foo(var) { //do something with var ... #if DEBUG_VERSION #include "debug.js" console.log('foo called with: ' + var); #endif }
Now as part of my build process, I run cpp against this file as either a debug version, or a production version.
Using ‘cpp -P -C -DDEBUG_VERSION=1′ will include the debug.js library, leave comments intact, and leave the console logging statements. Building a production version by preprocessing the source file(s) using ‘cpp -P -DDEBUG_VERSION=0′ strips ALL comments, and does not include any of the conditional code used in the debug version.
This allows me to write and debug code very rapidly, as well as use a lot of notes and comments - and for production, all of that gets removed automagically. Using this within an Ant build for example, I can combine this task with other tasks (like concatenating multiple Javascript files and compressing them using the YUI compressor) I have a very versatile and easy to use setup. I will post later about my build process, and using Ant in particular in the next couple of weeks.

