Using make file variables in C

I need to read a file in a C program, and I donโ€™t want to hardcode the path to this file. I want to provide this 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 this?

+7
source share
4 answers

This should probably be done with a command line parameter, but if you have to do this in a 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; } 

-D indicates the #define compilation time, which sets MYSTRING to "hello" .

Then, when you use MYSTRING in the code, it turns into a string. In this code example, I just pass it to printf , but you can also pass it to fopen per your requirement.

When you run this executable, the output is:

 [hello] 

This is not unlike a simple encoding of a value in the source code - you will have to recompile if you need to change the line (so I suggested the command line parameter in the first paragraph).

+16
source

You want to handle this by concatenating strings:

Makefile:

 PATH = "/usr/bin/" program: # whatever $CC /DPATH=$(PATH) 

Then in your C file you will have something like:

 fopen(PATH "xyz.txt", "r"); 

The compiler will combine the lines into one line during preprocessing.

+3
source

If you are gcc or any similar compiler, you can use the -D flag documented inside the man page.

To give a brief overview, you can do gcc -DSYMBOL=1 , and this will cause the compiler to add this to the code:

 #define SYMBOL 1 

So in your makefile you can set the make variable and then pass it to the gcc command line options.

+2
source

I am starting a makefile, and finally I got a better way to pass variables from makefile to #define and will not affect Escape.

1. pass the string

you can use the following code

 -D STRING_SAMPLE='"string sample"' 

equally

 #define STRING_SAMPLE "string sample" 

2. pass int or char

you can use the following code

 -D CHAR_SAMPLE="'\n'" 

equally

 #define CHAR_SAMPLE '\n' 

3. SampleCode

 //makefile sample CC = gcc CCFLAGS = -Wall -O //run `make test` in terminal test:main run clean run: @./main.e main: @$(CC) $(CCFLAGS) -c main.c -D STRING_SAMPLE='"string sample"' -D CHAR_SAMPLE="'\n'" -o main.o @$(CC) main.o -o main.e .PHONY:clean clean: @rm *.e @rm *.o 

and main.c

 //sample code in C #include "stdio.h" #include "string.h" int main(void){ puts("start test char"); printf("value(hex)==%.2x\n",CHAR_SAMPLE); puts("end test char"); int i; puts("start test string"); for (i=0; i< sizeof(STRING_SAMPLE); i++) { printf("value%d(hex)==<%.2x>\n",i,STRING_SAMPLE[i]); } puts("end test string"); } 
0
source

All Articles