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

pol*_*nux 5 c header

如果我想要使用包含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
Run Code Online (Sandbox Code Playgroud)

然后将proto.h包含在需要它的所有*.c文件中typedef

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

Kev*_*eer 9

这是正确的,但出于多种原因并非最佳解决方案.

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

出于这些原因,我建议在任何头文件中需要来自另一个头的定义(例如,在函数原型中使用宏或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
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)