问题
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.
回答1:
m4
is the tool that will convertDEF
to3
in this case. It is true thatsed
orawk
could serve the same purpose for this simple case butm4
is a much more powerful tool because it a) allows macros to be parameterized, b) includes conditionals, c) allows macros to be redefined through the input file, and much more. For example, one could write (in the filefor.pas.m4
, inspired by ratfor):
define(`LOOP',`for $1 := 1 to $2 do begin')dnl define(`ENDLOOP',`end')dnl LOOP(i,10) WriteLn(i); ENDLOOP;
... which produces the following output ready for the Pascal compiler when processed by m4 for.pas.m4
:
for i := 1 to 10 do
begin
WriteLn(i);
end;
- Removing general Pascal comments using
m4
would not be possible but creating a macro to include a comment that will be deleted by `m4' in processing is straightforward:
define(`NOTE',`dnl')dnl NOTE(`This is a comment') x := 3;
... produces:
x := 3;
Frequently-used macros that are to be expanded by m4
can be put in a common file that can be included at the start of any Pascal file that uses them, making it unnecessary to define all the required macros in every Pascal file. See include (file)
in the m4 manual.
来源:https://stackoverflow.com/questions/28978906/pre-processing-using-m4