存储大小未知:枚举

use*_*000 1 c enums

我在file1.h中定义了一个枚举.我想将此枚举作为参数在另一个文件file2.h中引用,而不包括file1.h.现在我必须从file3.h调用get_color()函数.我收到两种不同类型的错误:

  1. 从不兼容的指针类型[-Werror]传递'get_color'的参数1
  2. 错误1已解决,但我得到一个不同的错误:col的存储大小未知.

唯一的问题是我不能在file2.h中包含file1.h.请建议我如何解决这个问题.

file1.h

typedef enum {
    RED,
    BLUE,
    GREEN2,
} colors_t;
Run Code Online (Sandbox Code Playgroud)

file2.h

void get_color(enum colors_t *col);
Run Code Online (Sandbox Code Playgroud)

file3.h //选项1

#include "file1.h"
#include "file2.h" 
int main()
{
     colors_t col;
     get_color(&col); //error: passing argument 1 of 'get_color' from   incompatible pointer type [-Werror]

}
Run Code Online (Sandbox Code Playgroud)

file3.h //选项2

#include "file1.h"
#include "file2.h" 
int main()
{
     enum colors_t col;
     get_color(&col); //error: storage size of col isn't known.

}
Run Code Online (Sandbox Code Playgroud)

Sch*_*ern 5

签名get_colors应该是......

void get_color(colors_t *col);
Run Code Online (Sandbox Code Playgroud)

类型是colors_t.没有enum colors_t; 没有这种类型.


我相信问题在于理解如何typedef运作.typedef为类型创建名称.

typedef <type> <alias>;
Run Code Online (Sandbox Code Playgroud)

对于简单类型,这非常简单.这个别名unsigned charuint8_t.

typedef unsigned char uint8_t;
Run Code Online (Sandbox Code Playgroud)

对于结构和枚举,很容易混淆.

typedef enum {
    RED,
    BLUE,
    GREEN2,
} colors_t;
Run Code Online (Sandbox Code Playgroud)

类型是enum { RED, BLUE, GREEN2 }.别名是colors_t.

在这种情况下,该类型没有其他名称; 这是一个enum只能被引用的匿名者colors_t.

你可以给它起个名字.

typedef enum colors {
    RED,
    BLUE,
    GREEN2,
} colors_t;
Run Code Online (Sandbox Code Playgroud)

现在相同的类型可以称为enum colorscolors_t.

我建议不要这样做,因为它允许人们揭开由a提供的封装的面纱typedef.也就是说,如果每个人都使用colors_t你可以在幕后以微妙的方式改变它.