如何在C printf中使用宏?

kin*_*er1 0 c linux

我们的代码在printf中硬编码了至少20个不同文件的版本信息,例如: printf("Software version v11.2");这意味着每次更新时都会更改20个文件.

相反,我希望在common.h文件中使用宏和#include它,这样版本更新只是改变一个宏,就是这样.

我尝试过类似的东西:

#include <stdio.h>
#define VERSION "v11.2"
int main()
{
  printf("Trying to print macro: ", VERSION);
}
Run Code Online (Sandbox Code Playgroud)

但是这种"字符串""字符串"的样式在Java中不在C中.任何想法如何实现它?

我们将使用gcc进行编译.

注意:宏也用于一些典型的*.rc文件中,我们不能使用变量,并且某些地方使用SQL查询解析这些rc文件.所以我们不能使用像char ver [] ="v11.2"这样的变量

Wer*_*nze 11

这有两种可能的解决方案.

#include <stdio.h>
#define VERSION "v11.2"
int main()
{
  // Let printf insert the string when doing the output.
  printf("Trying to print macro: %s\n", VERSION);
  // Let the compiler concatenate the strings.
  puts("Trying to print macro: " VERSION);
  // Let the compiler concatenate the strings, can be assigned to a variable.
  const char buf[] = "Trying to print macro: " VERSION;
  puts(buf);
}
Run Code Online (Sandbox Code Playgroud)