Unit Tests in C

I strongly think that unit tests are absolutely necessary to keep the overall quality of ones code high. I’ve written about Unit Tests before, so I’ll continue on that trend.

Most high performance numerical codes use some variant of Fortran or just raw C (which is my staple language.) In that case, as Micheal Feathers rightly points out, unit tests can “collide” with C.

I’ll want to expand on his solution of link seams.

GNU/Linux (and other Unix-like operating systems I think), provide a mechanism of loading shared object files at runtime. Using dlopen(3) and dlsym(3) you can re-create much of the reflection functionality that the Java community enjoys. So by loading your unit test dynamically at runtime, and having a predetermined symbol that behaves as the entry point, you can nicely wrap your module/function with a unit test. Interface this with ctest from the cmake project, and you are set. If you want to have a private function whose symbol isn’t visible on the outside, make it static. The nm utility will give you a list of public symbols in an object.

I’m pretty sure this is supported across the board. I remember doing this under DOS using DJGPP (remember that?) so this isn’t exactly novel.

Comments are closed.