简体   繁体   English

如何在C printf中使用宏?

[英]How to use macro in a C printf?

Our code has versioning information hardcoded in printf in at least 20 different files like: printf("Software version v11.2"); 我们的代码在至少20个不同的文件中具有用printf硬编码的版本信息,例如: printf("Software version v11.2"); This means changing 20 files everytime there is an update. 这意味着每次更新时都更改20个文件。

Instead i wish to use a macro and #include it in a common.h file, such that version update is just changing one macro, that's all. 相反,我希望使用一个宏并将其包含在common.h文件中,以便版本更新仅更改一个宏,仅此而已。

I tried something like: 我尝试了类似的东西:

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

But this style of "string""string" works in Java not in C. Any ideas how to accomplish it? 但是这种“ string”“ string”样式在Java中不起作用,而在C语言中却没有。任何想法如何实现呢?

We will use the gcc for compilation. 我们将使用gcc进行编译。

NOTE: The macro is also used in some typical *.rc files, where we can't use a variable, and somewhere these rc files are parsed using SQL query. 注意: 该宏还用于一些典型的* .rc文件中,在这些文件中我们无法使用变量,并且在某些地方使用SQL查询来解析这些rc文件。 So we can't use variables like char ver[]="v11.2" 所以我们不能使用像char ver [] =“ v11.2”这样的变量

Here are two possible solutions. 这是两个可能的解决方案。

#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);
}
printf("Trying to print macro: %s", VERSION);

Is is a string, %s should work. 是一个字符串, %s应该可以工作。

int main()
{
  printf("Trying to print macro: %s", VERSION);
}

Try this 尝试这个

#define PRINT(format,args...)\
\
    do { \
        printf(" your data...");\
        } \
    } while(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM