在C语言中使用makefile变量
我需要在C程序中读取一个文件,我不想硬编码该文件的路径。我想将该路径作为Make变量提供,然后在C prog中使用它在C语言中使用makefile变量,c,file,makefile,C,File,Makefile,我需要在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. 我该怎么做 这可能应该使用命令行参数完成,但是,如果必
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;
}
这与简单地在源代码中硬编码值没有什么不同-如果希望更改字符串,则必须重新编译(这就是我在第一段中建议使用命令行参数的原因)。您希望通过字符串连接来处理此问题: 生成文件:
PATH = "/usr/bin/"
program: # whatever
$CC /DPATH=$(PATH)
然后在您的C文件中,您会有如下内容:
fopen(PATH "xyz.txt", "r");
在预处理过程中,编译器会将这些字符串连接在一起,形成一个字符串。如果您是gcc或任何类似的编译器,您可以使用
-D
标志,如文档所示
要快速概述,您可以执行gcc-DSYMBOL=1
,这将导致编译器将以下内容添加到代码中:
#define SYMBOL 1
因此,在makefile中,您可以设置一个make变量,然后将其传递给gcc命令行选项。我是makefile的初学者,我终于找到了一种更好的方法,可以将变量从
makefile
传递到#define
,并且不会受到转义的影响
##一,。传一串
您可以使用以下代码
-D STRING_SAMPLE='"string sample"'
-D CHAR_SAMPLE="'\n'"
等于
#define STRING_SAMPLE "string sample"
#define CHAR_SAMPLE '\n'
##二,。传递一个int或char
您可以使用以下代码
-D STRING_SAMPLE='"string sample"'
-D CHAR_SAMPLE="'\n'"
等于
#define STRING_SAMPLE "string sample"
#define CHAR_SAMPLE '\n'
##三,。样本码
# 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
和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");
}
//C语言中的示例代码
#包括“stdio.h”
#包括“string.h”
内部主(空){
puts(“开始测试字符”);
printf(“值(十六进制)=%.2x\n”,字符样本);
puts(“结束测试字符”);
int i;
puts(“启动测试字符串”);
对于(i=0;i
在编译时通过make设置路径
与硬编码没有什么不同;它仍然是在可执行文件中预定义的。您最好让它在运行时接受命令行参数或读取环境变量。@Ken:我相信,这比硬编码好。文件的位置因此程序的使用者而异。因此,我需要一种不需要修改/更改程序接口的方法。例如,对于consumer1,其makefile设置路径=/a/b/c;对于comsumer2,其makefile设置路径=/d/e/f/Cool……非常感谢。另一方面,我想,我可以在Makefile中将PATH设置为一个env变量,并将其与getenv()一起使用?@hari-不,那不行。Makefile确定编译时参数,但getenv()
在运行时工作。