【问题标题】:difference between stdint.h and inttypes.hstdint.h 和 inttypes.h 之间的区别
【发布时间】:2011-09-29 12:02:15
【问题描述】:

stdint.h 和 inttypes.h 有什么区别?

如果没有使用它们,则无法识别 uint64_t,但对于它们中的任何一个,它都是已定义的类型。

【问题讨论】:

  • inttypes.h #includes stdint.h.

标签: c uint64 stdint


【解决方案1】:

stdint.h

如果您想使用 C99 的指定宽度整数类型(即int32_tuint16_t 等),包含此文件是“最低要求”。 如果包含此文件,您将获得这些类型的定义,以便您能够在变量和函数的声明中使用这些类型,并对这些数据类型进行操作。

inttypes.h

如果包含此文件,您将获得 stdint.h 提供的所有内容(因为 inttypes.h 包含 stdint.h),但您还将获得执行printf 的便利和scanf(以及fprintffscanf 等)以可移植的方式使用这些类型。例如,您将获得PRIu64 宏,这样您就可以像这样printfuint64_t

#include <stdio.h>
#include <inttypes.h>
int main (int argc, char *argv[]) {

    // Only requires stdint.h to compile:
    uint64_t myvar = UINT64_C(0) - UINT64_C(1);

    // Requires inttypes.h to compile:
    printf("myvar=%" PRIu64 "\n", myvar);  
}

您希望将printf 与 inttypes.h 一起使用的一个原因是,例如,uint64_t 在 Linux 中是 long unsigned,但在 Windows 中是 long long unsigned。因此,如果您只包含 stdint.h(而不是 inttypes.h),那么,要编写上述代码并使其在 Linux 和 Windows 之间保持交叉兼容,您必须执行以下操作(注意丑陋的 #ifdef) :

#include <stdio.h>
#include <stdint.h>
int main (int argc, char *argv[]) {

    // Only requires stdint.h to compile:
    uint64_t myvar = UINT64_C(0) - UINT64_C(1);

    // Not recommended.
    // Requires different cases for different operating systems,
    //  because 'PRIu64' macro is unavailable (only available 
    //  if inttypes.h is #include:d).
    #ifdef __linux__
        printf("myvar=%lu\n", myvar);
    #elif _WIN32
        printf("myvar=%llu\n", myvar);
    #endif
}

【讨论】:

  • 谢谢,这是一个很好的答案(尽管我没有问最初的问题!)。为了补充 Mikko 的答案, inttypes.h 在 stdint.h 中复制(通过预处理器#include)。至少在我的 Linux 系统(GCC 4.5.2 和类似系统)上。
【解决方案2】:

See the wikipedia article for inttypes.h.

将 stdint.h 用于最小定义集;如果您还需要在 printf、scanf 等中对这些提供便携式支持,请使用 inttypes.h。

【讨论】:

  • 我来到 stackoverflow 以了解 stdint.h 和 inttypes.h 之间的区别 阅读了 wiki 文章,该文章告诉我 (u)intN_t 在两者中都可用。那么区别是什么呢?我应该包括哪些?
  • includes 并添加了一些 printf 宏。请参阅下面 Mikko Östlund 的回答。
  • 我得到:fatal error: inttypes.h: No such file or directory
  • @m4l490n 你在用-std=c99吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2020-05-10
  • 2014-09-20
  • 2010-10-28
  • 2015-10-04
  • 2012-08-12
  • 2011-02-18
相关资源
最近更新 更多