在C中使用makefile变量

har*_*ari 8 c makefile file

我需要读取C程序中的文件,我不想硬编码该文件的路径.我想将该路径作为Make变量提供,然后在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.
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

pax*_*blo 17

这可能应该使用命令行参数来完成,但是,如果必须在makefile中执行此操作,则可以使用以下命令:

$ 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;
}
Run Code Online (Sandbox Code Playgroud)

-D指定编译时#define这台MYSTRING"hello".

然后,当您MYSTRING在代码中使用时,它将变为字符串.在该示例代码中,我只是将其传递给printf您,但您可以fopen根据您的要求将其传递给它.

运行该可执行文件时,输出为:

[hello]
Run Code Online (Sandbox Code Playgroud)

这与简单地对源代码中的值进行硬编码没有什么不同 - 如果您希望更改字符串,则必须重新编译(这就是我在第一段中建议命令行参数的原因).

  • @hari - 不,那不行.Makefile确定编译时参数,但`getenv()`在运行时工作. (2认同)