中为Windows和Linux的跨平台定义64位整数

中为Windows和Linux的跨平台定义64位整数

本文介绍了在C ++中为Windows和Linux的跨平台定义64位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Windows(MinGW)和Linux(g ++)的C ++中编写跨平台代码。我习惯于在Linux中定义64位整数为long,但是当我移动到MinGW时,sizeof(long)返回4个字节。然后我发现我可以使用long long或__INT64在MinGW中定义64位整数。我有两个问题:



1.-为Windows和Linux定义64位整数的最便携的方式是什么?使用#ifdef,但我不知道这是否是最好的方法:

  #ifdef LINUX 
#define INT64 long
#elif WIN32
#define INT64 long long
#endif


b $ b

2 .- 我应该在MinGW中使用long long还是__INT64?

您可以使用 int64_t >,它在标题 cstdint 中定义。这是标准的C ++ 11。



请注意,如果您使用的平台不支持64位整数,则此类型可能不存在。



对于 long long ,这是另一种可能性。 long long 至少为64位宽。注意,它是标准的C ++ 11,即使它将工作在几个编译器,当使用C ++ 03。



如Pete Becker所述,您可以使用 int_least64_t 。如果你不介意使用正好的64位整数,但一些整数类型至少 64位宽,这是一个很好的选择。


I am trying to write cross-platform code in C++ for Windows(MinGW) and Linux(g++). I was used to define 64 bit integers in Linux as "long", but when I moved to MinGW, the sizeof(long) returned 4 bytes. Then I discovered that I can use "long long" or "__INT64" to define 64 bit integers in MinGW. I have two questions:

1.-What is the most portable way to define 64 bit integers for both Windows and Linux? I am currently using #ifdef, but I don't know if this is the best way to do it:

#ifdef LINUX
    #define INT64 long
#elif WIN32
    #define INT64 long long
#endif

2.-Should I use "long long" or "__INT64" in MinGW? and why?

解决方案

You could use the type int64_t, which is defined in the header cstdint. This is standard as of C++11.

Note that this type might not exist if the platform you're using does not support 64 bit integers.

As for long long, that is another possibility. long longs are at least 64-bits wide. Note that it is standard as of C++11 as well, even though it will work on several compilers when using C++03.

As mentioned by Pete Becker, you could use int_least64_t. This is a good choice if you don't mind using exactly 64 bit integers, but some integral type that is at least 64 bits wide.

这篇关于在C ++中为Windows和Linux的跨平台定义64位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:37