我需要在 C 程序中读取一个文件,我不想对该文件的路径进行硬编码。我想将该路径作为 Make 变量提供,然后在 C 程序中使用它。
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.
我该怎么做?
最佳答案
这可能应该使用命令行参数来完成,但是,如果您必须在 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;
}
-D
指定编译时 #define
将 MYSTRING
设置为 "hello"
。
然后,当您在代码中使用 MYSTRING
时,它会变成字符串。在该示例代码中,我只是将它传递给 printf
,但您同样可以根据您的要求将它传递给 fopen
。
当您运行该可执行文件时,输出为:
[hello]
这与在源代码中简单地硬编码值略有不同 - 如果您想要更改字符串,则必须重新编译(这就是我在第一段中建议使用命令行参数的原因)。
关于c - 在 C 中使用 makefile 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657551/