Using makefile variables in C
This probably should be done with a command line parameter but, if you must do it within the makefile, you can use the following:
$ cat makefile
qq: myprog.c makefile
gcc -DMYSTRING='"hello"' -o myprog -Wall myprog.c
$ cat myprog.c
#include <stdio.h>
int main(void) {
printf ("[%s]\n", MYSTRING);
return 0;
}
The -D
specifies a compile-time #define
which sets MYSTRING
to "hello"
.
Then, when you use MYSTRING
in the code, it's turned into the string. In that sample code, I simply pass it to printf
but you could equally well pass it to fopen
as per your requirement.
When you run that executable, the output is:
[hello]
This is little different to simply hard-coding the value in the source code - you will have to recompile if you ever want the string to change (which is why I suggested a command line parameter in the first paragraph).
If you are gcc or, any similar compiler, you can use the -D
flag, documented inside the manpage.
To give a quick overview, you can do gcc -DSYMBOL=1
, and this would result in the compiler adding this to the code:
#define SYMBOL 1
So, in your makefile, you can set a make variable, and then pass it to the gcc command line options.
You'd want to handle this via string concatenation:
makefile:
PATH = "/usr/bin/"
program: # whatever
$CC /DPATH=$(PATH)
Then in your C file you'd have something like:
fopen(PATH "xyz.txt", "r");
The compiler will concatenate the strings together into a single string during preprocessing.