Friday 16 June 2017

Putting self-tests in a C header file


You can compile a header file to C using gcc -x c like this:

gcc -x c -o feature-test feature.h

Without the -x c options it would have built a pre-compiled header instead of a program you can run.

But of course the compile will ultimately fail as you don't have a main( ) function, and when you think about it you know that you won't normally want one.

Except when compiling the top level header file directly.

The pre-processor symbol __INCLUDE_LEVEL__ is conveniently 0 for the top level file, which lets us do:

#if __INCLUDE_LEVEL__
int test1( ) {
  ...
}
...
int main(int argc, char **argv) {
  return test1() && test2() ... ;
}
#endif

So if the top level header file is build directly, then it gets a main and some test functions too.


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete