Search code examples
cbashmakefileterminal

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).


Solution

  • 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.