确定架构是 32 位还是 64 位的优雅而安全的方法 [英] Elegant and safe way to determine if architecture is 32bit or 64bit

查看:25
本文介绍了确定架构是 32 位还是 64 位的优雅而安全的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,是否有任何优雅且安全的方法来确定架构是 32 位还是 64 位.通过优雅,您可以想到精确、正确、简短、干净和聪明的方式.安全,从标准、C89/C99、操作系统独立性等方面考虑安全.

As title says, is there any elegant and safe way to determine if architecture is 32bit or 64bit. By elegant, you can think of precise, correct, short, clean, and smart way. By safe, think of safe in term of standard, C89/C99, and operating system independence.

推荐答案

指针的大小并不是一个真正值得测试的好东西 - 在标准 C 中没有太多可以用测试结果做的事情.

The size of pointers isn't really a good thing to test - there's not much in standard C that you can do with the result of that test anyway.

我的建议是测试((size_t)-1),C可以理解的最大对象大小:

My suggestion is test ((size_t)-1), the largest object size that C understands:

    if ((size_t)-1 > 0xffffffffUL)
    {
            printf("> 32 bits\n");
    }
    else
    {
            printf("<= 32 bits\n");
    }

如果它大于 0xffffffffUL 那么原则上你可以拥有大于 2**32 - 1 字节的对象,这似乎是一个比模糊的更有意义的测试"32 位对 64 位".

If it's greater than 0xffffffffUL then you can in principle have objects larger than 2**32 - 1 bytes, which seems like a more meaningful test than a nebulous "32 bits versus 64 bits".

(例如,如果您知道 size_t 的最大值仅为 2**32 - 1,那么尝试 mmap() 一个大于 1 或 2 GB 的区域.)

(For example, if you know that the maximum value of size_t is only 2**32 - 1, then there's no point trying to mmap() a region bigger than 1 or 2 GB.)

这篇关于确定架构是 32 位还是 64 位的优雅而安全的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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