tags:

views:

162

answers:

3
+1  Q: 

C macro processing

Hy. 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?

A: 

2 suggestions:

ie "don't try this at home".

tony
There's no C++ tag on this question, so Boost is not an appropriate suggestion.
caf
-1 Your post in no way answers OP's question
qrdl
A: 

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 lexar 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

jimka
Anyone have suggestions to a pure C regexp library?
jimka
PCRE? www.pcre.org
mcl
+1  A: 

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.

Remo.D
<shameless>I do have an example of a very simple macro system in my c-libutl package. It doesn't do all that you need, but in case it might be useful you can find it here: http://code.google.com/p/c-libutl/source/browse/trunk/examples/macro/macro.c </shameless> :)
Remo.D
I'll take look at it, thanks.
paleman