c++ - 如何将宏中#define 的值转换为 char* (c++)

标签 c++ macros directory

在一个.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/

相关文章:

c++ - 我不明白尝试使用字符串作为函数参数时遇到的错误

c++ - 是否可以将 MS 单元测试从 EXE 转发到 DLL?

directory - 通过终端使用 Google Drive 时无法访问的文件夹

macros - 如何将引用的 sexp 传递给宏

file - 如何使用javafx从目录中获取所有文件

java - Inno Setup Compiler - JavaFX 应用程序不写入文件

c++ - 使用笔在透明窗口上绘图

c++ - 使用 CGAL 进行网格 bool 运算

macros - OpenOffice 语法高亮

macros - 如何删除所有具有相似名称的表