C预处理程序:用前导零对String进行整型吗? [英] C Preprocessor: Stringify int with leading zeros?

查看:36
本文介绍了C预处理程序:用前导零对String进行整型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过此主题,它描述了通过执行"stringify"操作:

I've seen this topic which describes the "stringify" operation by doing:

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define MAJOR_VER 2
#define MINOR_VER 6
#define MY_FILE "/home/user/.myapp" STR(MAJOR_VER) STR(MINOR_VER)

是否可以使用前导零进行分类?假设在这种情况下,我的MAJOR_REV必须为两个字符"02",而MINOR_REV必须为两个字符"0006"如果我这样做:

Is it possible to stringify with leading zeros? Let's say my MAJOR_REV needs to be two characters "02" in this case and MINOR_REV 4 characters "0006" If I do:

#define MAJOR_VER 02
#define MINOR_VER 0006

在应用程序的其他位置,这些值将被视为八进制,这是我不希望的.

The values will be treated as octal elsewhere in the application, which I don't want.

推荐答案

没有干净也不方便的方法.就像一个挑战一样,这里有一个可能的解决方案":

No clean nor handy way to do it. Just as a challenge, here a possible "solution":

1)创建一个包含以下内容的头文件(例如"smartver.h")

1) create a header file (e.g. "smartver.h") containing:

#undef SMARTVER_HELPER_
#undef RESVER
#if VER < 10
#define SMARTVER_HELPER_(x) 000 ## x
#elif VER < 100
#define SMARTVER_HELPER_(x) 00 ## x
#elif VER < 1000
#define SMARTVER_HELPER_(x) 0 ## x
#else
#define SMARTVER_HELPER_(x) x
#endif
#define RESVER(x) SMARTVER_HELPER_(x)

2)在源代码中,无论何时需要带有前导零的版本号:

2) In your source code, wherever you need a version number with leading zeroes:

#undef VER
#define VER ...your version number...
#include "smartver.h"

这时,表达式 RESVER(VER)扩展为四位数的字符序列,而表达式 STR(RESVER(VER))是等价的字符串(注意:我已经使用了您在答案中发布的STR宏).

at this point, the expression RESVER(VER) is expanded as a four-digit sequence of character, and the expression STR(RESVER(VER)) is the equivalent string (NOTE: I have used the STR macro you posted in you answer).

在您的示例中,先前的代码与次要版本的大小写匹配,对其进行修改以与主要版本"的大小写匹配很简单.但实际上,我将使用一个简单的外部工具来生成所需的字符串.

The previous code matches the case of minor version in your example,it's trivial to modify it to match the "major version" case. But in truth I would use a simple external tool to produce the required strings.

这篇关于C预处理程序:用前导零对String进行整型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆