gpt4 book ai didi

c - 如何以及在何处将 stdint.h 类型定义包含在头文件中?

转载 作者:太空狗 更新时间:2023-10-29 14:54:13 30 4
gpt4 key购买 nike

如果我希望所有包含 proto.h 的 *.c 文件都使用 int32_t 而不是 int 将其写入名为的头文件是否正确proto.h:

#ifndef PROTO_H_INCLUDED
#define PROTO_H_INCLUDED
#ifndef STDINT_H_INCLUDED
#define STDINT_H_INCLUDED
typedef int int32_t;
typedef unsigned int uint32_t;
typedef size_t uint32_t;
#endif

然后将 proto.h 包含到所有需要此 typedef 的 *.c 文件中?

或者我应该将 stdint.h 包含到我所有的 *.c 文件中吗?

最佳答案

这是正确的,但由于多种原因,这不是最佳解决方案。

  1. 整理这份 typedef 列表需要额外的工作。它们已经在 stdint.h 中。
  2. 您的 typedef 在某些体系结构上不正确,并且您没有对此进行任何检查。如果有人看到 uint32_t,他们希望它是任何架构上的 32 位 unsigned int;这将是一个很难追踪的错误。
  3. 您的 proto.h 文件的用户并不清楚它包含 stdint.h。有人会说您应该包含尽可能少的文件;在我看来,更重要的是要清楚。删除用户 C 文件中的 proto.h 包含应该只需要删除对其中声明的函数的引用,而不是添加 stdint.h 的包含。为清楚起见,您应该将其添加到 .c 文件中,他们也会这样做。
  4. 您已经在 typedef 周围添加了额外的 include guards,这些不是必需的 - stdint.h(以及您将使用的所有其他 header )已经包含 include guards。

出于这些原因,我建议在任何需要来自另一个头文件的定义的头文件中(例如,要在函数原型(prototype)中使用宏或 typedef),您应该按如下方式构建文件:

proto.h

#ifndef PROTO_H_INCLUDED
#define PROTO_H_INCLUDED

// Typedefs for prototypes
#include <stdint.h>

unit32_t proto(int32_t *value, size_t length);

#endif

proto.c

#include <stdint.h>
#include "proto.h" // Forward declare functions in this file

unit32_t proto(uint32_t *value, size_t length)
{
// Do something
}

main.c

#include <stdint.h>
#include "proto.h"

int main(int argc, char *argv[])
{
uint32_t values[] = { 1, 2, 3 };
uint32_t result;
// Could do 'uint32_t result, values[] = { 1, 2, 3 };' (one line)
// but this is better for clarity
size_t len = sizeof(values) / sizeof(values[0]);

proto(values, len);
}

关于c - 如何以及在何处将 stdint.h 类型定义包含在头文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347879/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com