在一个.cpp中,我想输出一个文件到编译时创建的目录(由编译时决定)。我在我的 makefile 中通过 -DCOMPILETIME=$(stuff about time) 传递了这个值。我想将存储在 COMPILETIME 中的值传递给 sprintf,这样我就可以创建一个文件路径字符串,最终用于放置我的输出文件。
我试过:
#define str(x) #x
sprintf(filepath,"\"%s\file\"",str(COMPILETIME));
还有
#define str(x) #x
#define strname(name) str(name)
sprintf(filepath,"\"%s\file\"",strname(COMPILETIME));
但我只得到
"COMPILETIME/file"
作为输出。
最佳答案
您的宏没问题。这是一个测试程序:
#include <stdio.h>
#define str(x) #x
#define strname(name) str(name)
int main()
{
printf("\"%s/file\"\n",strname(COMPILETIME));
return 0;
}
构建命令:
cc -Wall -o soc soc.c
输出:
"COMPILETIME/file"
构建命令:
cc -Wall -o soc soc.c -DCOMPILETIME=abcd
输出:
"abcd/file"
在 gcc 4.9.2 下测试。
您在使用 fopen
时遇到的问题可能与:
sprintf(filepath,"\"%s\file\"",strname(COMPILETIME));
^^^^
做那个
sprintf(filepath,"\"%s\\file\"",strname(COMPILETIME));
^^^^
否则,您将转义字符 f
,它什么都不做。您还应该能够使用正斜杠而不是反斜杠。
sprintf(filepath,"\"%s/file\"",strname(COMPILETIME));
^^^^
关于c++ - 如何将宏中#define 的值转换为 char* (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31599000/