簡體   English   中英

Typedef適用於結構但不適用於枚舉,僅適用於C ++

[英]Typedef works for structs but not enums, only in C++

我有以下代碼:

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 %d\n", 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 %d\n", s.s1, s.s2, s.s3 );
}

注意我是如何以相同的方式對結構和枚舉進行類型化。 當我使用gcc -I. test.c -o test直接編譯時gcc -I. test.c -o test gcc -I. test.c -o test它工作正常,但是在用gcc -I. test_cpp.cpp -o test_cpp編譯時使用gcc -I. test_cpp.cpp -o test_cpp gcc -I. test_cpp.cpp -o test_cpp ,我收到以下錯誤:

./test_header.h:1:14: error: use of enum ‘_test_enum’ without previous declaration

所以我的問題是雙重的:為什么這在C中起作用而不是C ++,為什么編譯器接受結構但不接受枚舉?

在enum上面聲明結構時,我得到了相同的行為。 我正在使用GCC 4.8.2。

枚舉是一個整數類型,編譯器根據枚舉值的范圍選擇確切的類型。 所以你不能做一個enum的前向聲明。

ISO C標准禁止對enum類型進行前向引用。 我不完全確定,但我想這是確認它的摘錄:

6.7聲明

1 [...]

約束

2聲明應至少聲明聲明者(函數的參數或結構或聯合的成員除外),標記或枚舉的成員。

3 [...]

如果這是錯誤的,並且您知道哪個部分確切地引用了該問題,請更正我。

因此,您不能在C中使用枚舉的前向聲明。雖然,GCC允許它作為擴展,但如果啟用-Wpedantic開關肯定會發出警告。

順便說一下,你可以像這樣寫:

typedef enum {
  red,
  green,
  blue,
} test_enum;

並且根據標准完全沒問題,因此即使使用-Wpedantic -Werror也會編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM