2

I want to parse a file and bracket each line with #ifndef and #endif.

For example, starting with:

#define X 1
#define Y 2
#define Z 3

I want to generate:

#ifndef X
#define X 1
#endif
#ifndef Y
#define Y 2
#endif
#ifndef Z
#define Z 3
#end if

This awk script works in console, but it doesn't work inside make:

awk '{printf "#ifndef %s\n%s %s %s\n#endif\n", $2, $1, $2, $3}' globals.tmp > globals.h

When run inside of make, it outputs as follows:

awk: cmd. line:1: {printf "#ifndef %s\n%s %s %s\n#endif\n", , , , }
awk: cmd. line:1:                                           ^ syntax error
awk: cmd. line:1: {printf "#ifndef %s\n%s %s %s\n#endif\n", , , , }
awk: cmd. line:1:                                             ^ syntax error
awk: cmd. line:1: {printf "#ifndef %s\n%s %s %s\n#endif\n", , , , }
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf "#ifndef %s\n%s %s %s\n#endif\n", , , , }
awk: cmd. line:1:                                                 ^ syntax error
awk: cmd. line:1: {printf "#ifndef %s\n%s %s %s\n#endif\n", , , , }
awk: cmd. line:1:                                                  ^ unexpected newline or end of string

So it's obviously not pulling in the fields. I tried playing around with $1, $2, and $3: adding single, double and triple backslashes, changing the quotes, etc., nothing works. I know awk and make can be quirky, wondering if there is some "gotcha" I'm not getting?

  • 1
    You have to double the $ characters to keep make from evaluating them). That, and other useful information is in the manual page. (this is a duplicate, by the way). – Thomas Dickey Sep 8 '18 at 14:35
  • Bracket each line, or bracket each line starting #define? There's potentially quite a difference. (Unless every single line is a #define, of course. But you don't state that.) – roaima Sep 8 '18 at 15:32
  • @roaima - bracket each line, as it says – Buddy Sep 14 '18 at 14:41
  • @Buddy I know that's what it says. I was seeking confirmation you really meant that, because with lines other than those of the form #define K X your awk script would fail with its expectations of $1, $2, $3. So since you've confirmed that it's for "each line", what should happen when one or more of $1, $2, $3 are empty? – roaima Sep 14 '18 at 16:08
  • @roaima - the file is created by parsing a compile log to pull out all global definitions, with all lines are formatted as above - some definitions are already covered, and will cause a build error if redefined - the #ifndef #endif lines are used to protect against redefinition – Buddy Sep 14 '18 at 17:51

Browse other questions tagged or ask your own question.