如果我想要使用包含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文件中?
这是正确的,但出于多种原因并非最佳解决方案.
stdint.h.uint32_t,他们希望它在任何架构上都是32位无符号整数; 这将是一个令人讨厌的错误追踪.proto.h文件的用户不清楚它包含stdint.h.有些人会说你应该尽量少包含文件; 在我看来,明确更重要.删除proto.h用户C文件中的包含应该只需要删除对其中声明的函数的引用,而不是添加stdint.h的包含..c为了清楚起见,您应该将其添加到文件中,并且他们也希望这样做.出于这些原因,我建议在任何头文件中需要来自另一个头的定义(例如,在函数原型中使用宏或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)