I need to read a file in a C program and I do not want to hardcode the path to that file. I want to provide that path as a Make variable and then use it in C prog.
file name is xyz.txt and I want to do something like this in C prog:
fopen ("PATH/xyz.txt", "r");
here PATH is specified in make command that compiles this file.
How can I do that?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With