Fox1942
Fox1942

Reputation: 366

How to properly escape # character in a makefile?

I am learning about makefiles and for trying things out I wrote a makefile containing this text below:

blah: blah.o
        cc blah.o -o blah
blah.o: blah.c
        cc -c blah.c -o blah.o
blah.c:
        echo '\#include <stdio.h>  int main(){ return 0; }' > blah.c
clean:
        rm -f blah.o blah.c blah

Unfortunately, by entering the make command I got this error:

blah.c:1:1: error: stray ‘\’ in program
 \#include <stdio.h>  int main(){ return 0; }
 ^
blah.c:1:2: error: stray ‘#’ in program
 \#include <stdio.h>  int main(){ return 0; }
  ^
blah.c:1:11: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
 \#include <stdio.h>  int main(){ return 0; }
           ^
Makefile:4: recipe for target 'blah.o' failed
make: *** [blah.o] Error 1

I don't really understand the error as I escaped the # character properly (as I suppose).

Upvotes: 0

Views: 804

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126203

The problem is that there isn't any need to escape characters in '...' strings. They are all literal, including the \ (i.e., there isn't any way to escape characters in '...' strings). So you're getting a literal \ before the # in blah.c, which prevents the C preprocessor from noticing it as a directive.

Remove the \ and it should work fine.

Upvotes: 1

MadScientist
MadScientist

Reputation: 100836

This is a shell question, not a makefile question. If you run the command at your shell prompt, not from a makefile, you'll see the same behavior:

$ echo '\#include <stdio.h>  int main(){ return 0; }' > blah.c
$ cat blah.c
\#include <stdio.h>  int main(){ return 0; }

This is simple shell quoting rules. If you use a single quote in the shell then nothing inside the single quoted string will be interpreted by the shell. It will be written as-is. So, don't quote it:

blah.c:
    echo '#include <stdio.h>  int main(){ return 0; }' > blah.c

Upvotes: 1

Related Questions