Cross platform format string for variables of type size

On a cross platform c/c++ project (Win32, Linux, OSX), I need to use the *printf functions to print some variables of type size_t. In some environments size_t's are 8 bytes and on others they are 4. On glibc I have %zd, and on Win32 I can use %Id. Is there an elegant way to handle this?


PRIuPTR宏(来自<inttypes.h>)为uintptr_t定义了一个十进制格式,该格式应该总是足够大,以便可以在不截断的情况下对其施加size_t ,例如

fprintf(stream, "Your size_t var has value %" PRIuPTR ".", (uintptr_t) your_var);

There are really two questions here. The first question is what the correct printf specifier string for the three platforms is. Note that size_t is an unsigned type.

On Windows, use " %Iu ".

On Linux and OSX, use " %zu ".

The second question is how to support multiple platforms, given that things like format strings might be different on each platform. As other people have pointed out, using #ifdef gets ugly quickly.

Instead, write a separate makefile or project file for each target platform. Then refer to the specifier by some macro name in your source files, defining the macro appropriately in each makefile. In particular, both GCC and Visual Studio accept a 'D' switch to define macros on the command line.

If your build system is very complicated (multiple build options, generated sources, etc.), maintaining 3 separate makefiles might get unwieldly, and you are going to have to use some kind of advanced build system like CMake or the GNU autotools. But the basic principle is the same-- use the build system to define platform-specific macros instead of putting platform-detection logic in your source files.


The only thing I can think of, is the typical:

#ifdef __WIN32__ // or whatever
#define SSIZET_FMT "%ld"
#else
#define SSIZET_FMT "%zd"
#endif

and then taking advantage of constant folding:

fprintf(stream, "Your size_t var has value " SSIZET_FMT ".", your_var);
链接地址: http://www.djcxy.com/p/72210.html

上一篇: 是否有打印二进制格式的printf转换器?

下一篇: 跨平台格式字符串,用于字体大小的变量