C Preprocessor: Stringify int with leading zeros?

旧时模样 提交于 2021-02-07 18:27:27

问题


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)

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.


回答1:


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

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) In your source code, wherever you need a version number with leading zeroes:

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

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.




回答2:


I believe in the example provided by the question sprintf is the correct answer.

That said, there are a few instances where you really want to do this and with C preprocessor if there is a will and somebody stupid enough to write the code there is typically a way.

I wrote the macro FORMAT_3_ZERO(a) which creates a three digit zero padded number using brute force. It is in the file preprocessor_format_zero.h found at https://gist.github.com/lod/cd4c710053e0aeb67281158bfe85aeef as it is too large and ugly to inline.

Example usage

#include "preprocessor_format_zero.h"

#define CONCAT_(a,b) a#b
#define CONCAT(a,b) CONCAT_(a,b)

#define CUSTOM_PACK(a) cp_ ## a __attribute__( \
        (section(CONCAT(".cpack.", FORMAT_3_ZERO(a))), \
        aligned(1), used))

const int CUSTOM_PACK(23);


来源:https://stackoverflow.com/questions/28571516/c-preprocessor-stringify-int-with-leading-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!