Visual Studio and code generation
I’m a big fan of code generation. It fills the two basic needs of every good programmer, to maximize laziness, and to extend one’s own hubris. That, and it makes DRY possible.
Hooking code generation into a build system is trivial on most platforms, but Visual Studio presents a few unique problems: namely a poorly documented (but feature-rich) custom build system. Not only can the build system can be tamed, but you can do some cool stuff with it.
Here are a few of the things I’ve learned while using it:
- Don’t configure code generation in the pre/post build steps (seems the obvious place, but it doesn’t handle dependencies/changes)
- Calling Cygwin/Perl scripts is possible, but you’ll need to thunk them with a batch file to proxy build environment paths usefully1 (helps prevent brittle paths)
- Add code generation tools as source files, and set them as a
custom build toolvia their properties dialog2 - Set the custom tool’s file dependencies (and command line) in the same properties dialog (under
Custom build step - General) - From your code generation script, you can emit errors, warnings, and info messages to
STDERRthat the Visual Studio can understand and display in its rich error/warning/info viewer (just follow the same formatting as the C/C++ compiler) - To stop a build on errors, you can either emit
errormessages or you can return a non-zero value from your script
Most of my code-gen scripts are written in Perl as simple sed-style scripts. They’re unixy in the sense that they mash a few scripts together (cat $file | script.pl > $file2), and are easy to maintain and test. Python/Ruby/Sed would work just as well, given a reasonable Cygwin install.3.

RSS![1 comment [Comment]](/images/comment.png)
