2

I am writing a pre-processor for Free-Pascal (Course Work) using m4. I was reading the thread at stackoverflow here and from there reached a blog which essentially shows the basic usage of m4 for pre-processing for C. The blogger uses a testing C file test.c.m4 like this:

#include 

define(`DEF', `3')

int main(int argc, char *argv[]) {
        printf("%d\n", DEF);
        return 0;
}

and generates processed C file like this using m4, which is fine.

$ m4 test.c.m4 > test.c
$ cat test.c
#include <stdio.h>



int main(int argc, char *argv[]) {
    printf("%dn", 3);
    return 0;
}

My doubts are:
1. The programmer will write the code where the line

    define(`DEF', `3')

would be

    #define DEF 3

then who converts this line to the above line? We can use tool like sed or awk to do the same but then what is the use of m4. The thing that m4 does can be implemented using sed also.
It would be very helpful if someone can tell me how to convert the programmer's code into a file that can be used by m4.

2. I had another issue using m4. The comment in languages like C are removed before pre-processing so can this be done using m4? For this I was looking for commands in m4 by which I can replace the comments using regex and I found regexp(), but it requires the string to be replaced as argument which is not available in this case. So how to achieve this?

Sorry if this is a naive question. I read the documentation of m4 but could not find a solution.

4

1 回答 1

2
  1. m4是在这种情况下将转换为的工具DEF3确实,sed或者awk可以为这个简单的案例提供相同的目的,但m4它是一个更强大的工具,因为它 a) 允许对宏进行参数化,b) 包括条件,c) 允许通过输入文件重新定义宏,等等更多的。例如,可以写(在文件for.pas.m4中,受ratfor启发):
define(`LOOP',`for $1 := 1 to $2 do
begin')dnl
define(`ENDLOOP',`end')dnl

LOOP(i,10)
  WriteLn(i);
ENDLOOP;

...在处理时为 Pascal 编译器生成以下输出m4 for.pas.m4

for i := 1 to 10 do
begin
        WriteLn(i);
end;
  1. 使用删除一般 Pascal 注释m4是不可能的,但创建一个宏以包含在处理过程中被“m4”删除的注释很简单:
define(`NOTE',`dnl')dnl
NOTE(`This is a comment')
      x := 3;

...产生:

    x := 3;

常用的扩展宏m4可以放在一个公共文件中,该文件可以包含在任何使用它们的 Pascal 文件的开头,从而无需在每个 Pascal 文件中定义所有必需的宏。请参阅m4手册include (file)

于 2015-03-27T00:52:29.113 回答