开发者

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?


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.


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:

  • use boost wave (http://www.boost.org/doc/libs/1_40_0/libs/wave/index.html)
  • use the preprocessor that comes with your compiler

ie "don't try this at home".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜