In a recent project I have been experimenting with alternative preprocessors for generating combinatorially exploding volumes of code via meta-programming — something the traditional C preprocessor does not do easily because it was designed to have robust termination qualities. m4 is particularly appealing because it is present on most POSIX compliant systems and rules for *.m4
files can be expressed in my Makefile
directly using the shell (so I wouldn’t need to pull in a preprocessing library like Boost).
I couldn’t find many examples on the web which show very basic usage of m4 as a preprocessor, so I thought it would be useful to produce a very simple demonstration. Hypothetically wanting to avoid the regular C preprocessor for some reason, I have produced a testing C file like so;
#include define(`DEF', `3') int main(int argc, char *argv[]) { printf("%d\n", DEF); return 0; }
Preprocess it using m4
:
$ m4 test.c.m4 > test.c $ cat test.c #include <stdio.h> int main(int argc, char *argv[]) { printf("%dn", 3); return 0; }
And finally, compile and test with clang
;
$ clang test.c $ ./a.out 3
I will be writing a continuation to this post showing some more advanced things you can do with m4
that the traditional C preprocessor cannot, namely, automatically generating Duff’s device.