是否可以在不使用第三方库的情况下在运行时告诉 C 中整数类型有多少字节

Is it possible without the use of a third party library to tell how many bytes an integer type is in C at runtime

我希望在运行时探测一个 int 在运行时的字节数,而不用超过 POSIX C。

基本上,我的想法是寻找一种方法来检查 UINT_MAX 的系统限制,而无需让我的二进制文件在编译时依赖该信息。我首先想到尝试 sysconf() 但该变量未指定为可以使用的变量。

编辑 1: 为了澄清我正在做的事情是在阅读 POSIX 1003.1-2017 od 实用程序规范的基础上构建我自己的 od 程序。

特别是根据我对扩展描述中这些行的阅读和解释。

The default number of bytes transformed by output type specifiers d, f, o, u, and x corresponds to the various C-language types as follows. If the c99 compiler is present on the system, these specifiers shall correspond to the sizes used by default in that compiler. Otherwise, these sizes may vary among systems that conform to POSIX.1-2017. For the type specifier characters d, o, u, and x, the default number of bytes shall correspond to the size of the underlying implementation's basic integer type

我读到这意味着默认值是基于 运行 系统的环境而不是编译器

编辑2: sizeof 是我在反思中寻找的东西我意识到我最初的想法对于没有 libc 的环境中的静态链接二进制文件没有意义。

谢谢大家

如果您想知道 int 您的 可执行文件使用的大小,那么您可以使用 sizeof 因为大小在蜂鸣后不会改变已编译(即使你 运行 它在另一个处理器上)。

如果你想知道如果你的程序是在这台机器上编译的 int 的大小,那么最简单的方法可能是编译和 运行ning 像这样的东西:

int main() {
    printf("%zu\n", sizeof(int));
}

(或者您可以在 运行ning 机器上为 UINT_MAX grep include 目录)

如果您想在不同架构之间移动 int,那就完全不同了。

如果没有解决问题,请说明您的意图。

编辑:

grep /usr/include/limits.h -e 'UINT_MAX' --color

效果很好。

如果你还想在运行时间内完成你可以使用下面的-

unsigned char myIntegerSizeOf(void) {
    int a[] = { ~0, 0 } ;
    unsigned char *a_ptr = (unsigned char *)&a[0] ;
    unsigned char count = 0 ;

    while (*a_ptr == 0xFF) { 
        count++ ; 
        a_ptr++ ;
    }

    return count;
}

count 包含答案。