Search code examples
cmacrosc-preprocessorkernighan-and-ritchie

C macro processing


I'm thinking about best way to write C define processor that would be able to handle macros. Unfortunately nothing intelligent comes to my mind. It should behave exactly like one in C, so it handles expressions like this:

#define max(a, b) (a > b ? a : b)

 printf("%d\n", max(a, b));

Or this:

#define F 10
#define max(a, b) (a > b ? a : b)

 printf("%d\n", max(a, F));

I know about install and lookup functions from K&R2, what else do I need for replacing text inside parenthesis? Does anyone have any advice or some pseudo-code maybe? I know it's complex task, but still, what would be best possible way to do it?


Solution

  • Macro processors are very interesting but can became a difficult beast to tame (think about recursive expansions, for example).

    You can look at the implementation of already existing macro processors like M4 (http://www.scs.stanford.edu/~reddy/links/gnu/m4.pdf).

    In very general terms you will need:

    • a parser that will first extract the macro definitions from your files (deleting them from the file, of course)
    • another parser that identify where macros need to be expanded and performs the expansion (e.g. you will want to skip strings and comments!)

    I think it's a very interesting exercise. The proper data structure to handle all this is not trivial.