我有以下代码:
test_header.h:
typedef enum _test_enum test_enum;
enum _test_enum
{
red,
green,
blue
};
typedef struct _test_struct test_struct;
struct _test_struct
{
int s1;
int s2;
int s3;
};
test.c:
#include <test_header.h>
#include <stdio.h>
int main()
{
test_struct s;
s.s1=1;
s.s2=2;
s.s3=3;
printf("Hello %d %d %dn", s.s1, s.s2, s.s3 );
}
test_cpp.cpp:
extern "C"{
#include <test_header.h>
}
#include <stdio.h>
int main()
{
test_struct s;
s.s1=1;
s.s2=2;
s.s3=3;
printf("Hello %d %d %dn", s.s1, s.s2, s.s3 );
}
注意我是如何以相同的方式对结构和枚举进行类型定义的。当我用gcc -I. test.c -o test
在直C中编译时,它工作得很好,但当用gcc -I. test_cpp.cpp -o test_cpp
在C++中编译时我会得到以下错误:
./test_header.h:1:14: error: use of enum ‘_test_enum’ without previous declaration
所以我的问题有两个:为什么这在C中有效,而在C++中无效,为什么编译器接受结构而不接受枚举?
在枚举上方声明结构时,我会得到相同的行为。我使用的是GCC 4.8.2。
枚举是一个整数类型,编译器根据枚举值的范围选择确切的类型。所以不能对枚举进行正向声明。
ISO C标准禁止对enum
类型的前向引用。我不完全确定,但我想这是证实这一点的摘录:
6.7声明
1[…]
限制
2声明书须至少声明一名声明人(函数的参数或结构或联合的成员)标记或枚举的成员。
3[…]
请,如果这是错误的,并且你知道哪一节确切地提到了这个问题,请纠正我。
因此,不允许在C中使用枚举的正向声明。尽管GCC允许将其作为扩展,但如果启用-Wpedantic
开关,肯定会发出警告。
顺便说一下,你可以这样写:
typedef enum {
red,
green,
blue,
} test_enum;
并且根据标准它是非常好的,因此即使使用-Wpedantic -Werror
也可以编译。