简体   繁体   English

32位和64位Linux机器中4字节类型之间的差异

[英]Difference between 4-byte types in 32-bit and 64-bit Linux machines

I am porting our Linux C++ project from 32-bit to 64-bit. 我正在将我们的Linux C ++项目从32位移植到64位。

In our 32-bit system, "long" is 4-bytes long. 在我们的32位系统中,“ long”为4个字节长。 But when we built our project in 64-bit mode, we noticed that "long" is taking 8-bytes. 但是,当我们以64位模式构建项目时,我们注意到“ long”占用了8个字节。 Since we need 4-byte long type, we used "int" and confirmed that it is indeed 4-bytes long. 由于我们需要4字节长的类型,因此我们使用了“ int”并确认其确实为4字节长。 And we were hoping that our code works seamlessly. 我们希望我们的代码能够无缝运行。

But unfortunately no, even though "long" in 32-bit mode and "int" in 64-bit mode are 4-bytes long both, our code is failing. 但是不幸的是,即使在32位模式下的“长”和在64位模式下的“ int”都长4个字节,我们的代码还是失败了。

Could someone please let us know if there is a difference (in layout or something else) between "long" in 32-bit mode and "int" in 64-bit mode? 有人可以让我们知道32位模式下的“长”和64位模式下的“ int”之间是否存在差异(布局或其他方面)? Even though both are 4-bytes long? 即使两个都是4字节长?

  • Machine: Linux x86_64 机器:Linux x86_64
  • OS: CentOS 6.6 作业系统:CentOS 6.6
  • gcc: 4.9.2 gcc:4.9.2

If you need byte-length specific data types, look into int32_t and uint32_t from cstdint . 如果需要特定于字节长度的数据类型,请从cstdint查看int32_tuint32_t

The types are guaranteed to be the given length, signed and unsigned. 这些类型保证为给定的长度(带符号和无符号)。

Thanks everyone. 感谢大家。 The issue was something local/specific to our code, where we were making an assumption that pointers are always 4-bytes long. 问题是我们的代码是本地的/特定的,我们假设指针的长度始终为4个字节。 When we were dereferencing them, we were casting them to 4-byte variables and were losing precision. 当我们取消引用它们时,我们将它们强制转换为4字节变量,并且失去了精度。 This was causing crashes. 这导致崩溃。 Since this is a large codebase developed by many people over many years, there was lot of legacy code with these assumptions, I had to go over all the pointers and modify them. 由于这是许多人多年来开发的大型代码库,因此有许多基于这些假设的遗留代码,因此我不得不遍历所有指针并进行修改。 And finally we have ported our code successfully to 64-bit mode. 最后,我们已成功将代码移植到64位模式。

Take a look at this - Size guarantees in C++ . 看看这个-C ++中的Size保证 The built-in types (int , long etc.) satisfy some minimum sizes but they need not be 4 bytes on every system. 内置类型(int,long等)满足一些最小大小,但在每个系统上不必为4个字节。 You can use fixed width types (as mentioned in a comment by dwcanillas). 您可以使用固定宽度类型(如dwcanillas的评论中所述)。

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

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