Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using makefile variables in C

Tags:

c

file

makefile

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?

like image 490
hari Avatar asked Apr 14 '11 01:04

hari


2 Answers

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

like image 118
paxdiablo Avatar answered Sep 25 '22 07:09

paxdiablo


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.

like image 22
Jerry Coffin Avatar answered Sep 21 '22 07:09

Jerry Coffin