C语言 头文件中的枚举声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17987079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:02:36  来源:igfitidea点击:

enum declaration in header file

cenumsheader-files

提问by Jonas K

I have files A.c , B.c and B.h . In A.c there is an

我有文件 Ac , Bc 和 Bh 。在 Ac 中有一个

enum CMD{
    FIRST,
    SECOND,
    THIRD,
};

and later in that file there is

后来在那个文件中有

bool function(...){
//...
enum CMD data_type = FIRST;
//...
}

In file B.c I need to use

在文件 Bc 我需要使用

if (data_type == FIRST){...}

I tried to include in B.h this:

我试图在 Bh 中包含以下内容:

extern enum CMD data_type;

And included #include "B.h" in A.c and B.c . All files are in the propper folders of the project. But no cigar :( The line in B.c gives this:

并在 Ac 和 Bc 中包含 #include "Bh" 。所有文件都在项目的propper文件夹中。但是没有雪茄 :( Bc 中的行给出了这个:

20: identifier "FROM_SMS" is undefined
70: incomplete type is not allowed

How do I make this work. The A.c file is writen by someone else and I'm modifiing the code with B.c . The original code is a mess and I wan to fidlle with it as less as possible :) Architecture ie STM32 and I'm using uVision 3 IDE.

我如何使这项工作。Ac 文件是由其他人编写的,我正在用 Bc 修改代码。原始代码一团糟,我想尽可能少地使用它:) 架构,即 STM32,我正在使用 uVision 3 IDE。

Thank you

谢谢

回答by Jean-Micha?l Celerier

An enum is a type, you should put in in the .h.

枚举是一种类型,您应该放入 .h 中。

externkeyword is for variables.

extern关键字用于变量。

Edit: Sorry, I had badly read your code.

编辑:对不起,我读错了你的代码。

Here the problem is that you will try to use the enum without having it defined. Think that when a compiler compiles something, it takes every .c file separately, and then "copies" the content of the include into the c file.

这里的问题是您将尝试使用枚举而不定义它。认为当编译器编译某些东西时,它会分别获取每个 .c 文件,然后将包含的内容“复制”到 c 文件中。

So here you will have b.c which includes b.h but since the declaration of your type is in a.c, the compiler has no way of knowing it, hence throwing an error when trying to compile b.c.

所以在这里你会有 bc 包含 bh 但由于你的类型声明在 ac 中,编译器无法知道它,因此在尝试编译 bc 时抛出错误

To solve it, just declare your type at the top of b.h and include it in both files, or create a "myenum.h" file which you include in the .h / .c files that require it.

要解决它,只需在 bh 的顶部声明您的类型并将其包含在两个文件中,或者创建一个“myenum.h”文件,将其包含在需要它的 .h / .c 文件中。

回答by Grissiom

enumis just an other type of define. It only works in current translation unit.

enum只是另一种类型的define. 它仅适用于当前翻译单元。