定义用于多个文件的枚举数据类型
Define a enum data types for use in several files
我有几个文件,比如
main.c、main.h、some_funcs.c 和 some_funcs.h.
main.h is included in main.c
main.h include some_funcs.h
some_funcs.c include some_funcs.h
当我现在定义一个新的数据类型时:
//Datatypes
enum _bool {
false = 0,
true = 1
};
typedef enum _bool Bool;
如果我在例如main.h 并想在 some_func.c 中使用它是行不通的。有没有办法在某处定义它而不总是在定义它的地方包含 header?
Is there a ways to define it somewhere without always include the header where it is defined?
没有。
您必须在每个源文件中包含 header。
通常的做法是拥有自己的 typdef.h
。在其中定义您自己的数据类型并将其包含在您感兴趣的源文件中。
将定义放入some_funcs.h
。这将使它在 main.h、main.c、some_funcs.h 和 some_funcs.c 中可见。
一个更通用的解决方案是将常用数据类型放入一个名为 common.h
的文件中。
然后您将此文件包含在所有头文件中。
这将是 common.h
文件的内容。 ifdef
是忽略已经包含的文件内容。
#ifndef COMMON_H
#define COMMON_H
//Datatypes
enum _bool {
false = 0,
true = 1
};
typedef enum _bool Bool;
#endif
Is there a ways to define it somewhere without always include the
header where it is defined?
听起来我可以在不定义类型的情况下使用类型的定义。:)
您应该包括 header 文件,其中枚举和 typedef 在每个使用它的模块中定义。
考虑到 1) 在 C 中键入 _Bool
和 2) 标准 header <stdbool.h>
,其中宏 bool
、false
和true
已经定义。
我有几个文件,比如 main.c、main.h、some_funcs.c 和 some_funcs.h.
main.h is included in main.c
main.h include some_funcs.h
some_funcs.c include some_funcs.h
当我现在定义一个新的数据类型时:
//Datatypes
enum _bool {
false = 0,
true = 1
};
typedef enum _bool Bool;
如果我在例如main.h 并想在 some_func.c 中使用它是行不通的。有没有办法在某处定义它而不总是在定义它的地方包含 header?
Is there a ways to define it somewhere without always include the header where it is defined?
没有。
您必须在每个源文件中包含 header。
通常的做法是拥有自己的 typdef.h
。在其中定义您自己的数据类型并将其包含在您感兴趣的源文件中。
将定义放入some_funcs.h
。这将使它在 main.h、main.c、some_funcs.h 和 some_funcs.c 中可见。
一个更通用的解决方案是将常用数据类型放入一个名为 common.h
的文件中。
然后您将此文件包含在所有头文件中。
这将是 common.h
文件的内容。 ifdef
是忽略已经包含的文件内容。
#ifndef COMMON_H
#define COMMON_H
//Datatypes
enum _bool {
false = 0,
true = 1
};
typedef enum _bool Bool;
#endif
Is there a ways to define it somewhere without always include the header where it is defined?
听起来我可以在不定义类型的情况下使用类型的定义。:)
您应该包括 header 文件,其中枚举和 typedef 在每个使用它的模块中定义。
考虑到 1) 在 C 中键入 _Bool
和 2) 标准 header <stdbool.h>
,其中宏 bool
、false
和true
已经定义。