Question

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?

Was it helpful?

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.

OTHER TIPS

This is a pattern matching problem, you should take a look at regular expressions to start with, then when you've grasped the theory on that you could move on to reading about lexers.

A regular expression is basically matching a string to a predefined pattern.

Some regexp (short for regular expression) software/libraries:
- Boost.Regexp
- GNU C library regexp
- PCRE

And a lexer is a piece of software that does something with the matched text, for example, replacing that piece of text with some other piece of text, basically what you seem to need.

Some known lexers:
- flex
- Boost.Wave

2 suggestions:

ie "don't try this at home".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top