2017-04-25 67 views
1

我有一个在file1.h中定义的枚举。我想把这个枚举作为另一个文件file2.h中的一个参数,而不包括file1.h。现在我必须从file3.h中调用get_color()函数。我得到两个不同的错误类型:存储大小未知:枚举

  1. 通过从兼容的指针类型“get_color”的参数1 [-Werror]
  2. 错误1解决了,但我得到一个不同的错误:山坳ISN的存储大小不知道。

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

file1.h

typedef enum { 
    RED, 
    BLUE, 
    GREEN2, 
} colors_t; 

file2.h

void get_color(enum colors_t *col); 

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] 

} 

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. 

} 
+0

我可能是错的,但是这不是类型定义是如何工作的。它是'colors_t',成为类型,而不是'enum colors_t'。就像结构一样。 – grochmal

+0

请注意,应该是'file3.c'或'main.c',而不是'file3.h'。如果你在一个文件中有函数定义,它可能不是头文件。 – Schwern

+1

如果你想使用'enum colors_t'和'colors_t',写:'typedef enum colors_t RED, BLUE, GREEN2, } colors_t;'。否则,选择一个并坚持下去。 –

回答

5

get_colors签名应该是...

void get_color(colors_t *col); 

类型是colors_t。不是enum colors_t;没有这种类型。


我相信问题是了解typedef如何工作。 typedef为类型创建一个名称。

typedef <type> <alias>; 

对于简单的类型,这是非常简单的。这个别名unsigned charuint8_t

typedef unsigned char uint8_t; 

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

typedef enum { 
    RED, 
    BLUE, 
    GREEN2, 
} colors_t; 

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

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

你可以给它一个名字。

typedef enum colors { 
    RED, 
    BLUE, 
    GREEN2, 
} colors_t; 

现在同样的类型可以被称为enum colorscolors_t

我建议不要这样做,因为它可以让人们穿透由typedef提供的封装面纱。也就是说,如果每个人都使用colors_t,则可以在幕后以微妙的方式更改它。

1

只需更改您的代码:

typedef enum { 
    RED, 
    BLUE, 
    GREEN2, 
} colors_t; 

void get_color(colors_t *col) 
{ 
    /// get_color body 
} 

int main(int argc, char **argv) 
{ 
    colors_t col; 
    get_color(&col); 

    return 0; 
}