Forward listing declaration in C headers used in C ++ code?

You cannot forward an enum declaration in C ++ , but you can in C.

For a C code base that uses some C ++ code, is there a way to use the declared cast in C that does not cause errors if this header is used in C ++ (in a block extern "C" {..})?

Example:

extern "C" {
    enum MyEnum;
}
int main() { return 0; }

GCC gives an error:

error: use of enum ‘MyEnum’ without previous declaration
  enum MyEnum;
       ^~~~~~

Clang also fails:

error: ISO C++ forbids forward references to 'enum' types
        enum MyEnum;

To give some context, it is mainly a C base, where a small C ++ module includes a header for C code. I can hack a bit so that C ++ ignores the enumeration, but would like to know if C ++ can use C headers in this case.


: , C , , , - : GCC/CLANG/MSVC.

+4
3

C . C . , . , inteegral, .

typedef enum e12 { ONE, TWO } e12;
typedef enum e34 { THREE, FOUR } e34;
int main () {
    e12 one = ONE;
    e34 three = THREE;
    one = three;
    three = ONE;
    return one + three;
}

C gcc -Wall -Wextra -Wpedantic. (, ++).

,

#ifdef __cplusplus
   enum MyEnum : int;
#else
   typedef int MyEnum; // 'enum MyEnum' would give no improvement over this
#endif
+3

- ++, ++ 11. " ", " ", : , .

: . cppreference:

enum-key attr(optional) nested-name-specifier(optional) identifier enum-base(optional) ;(2) (since C++11)

2) enum: , : . . , ( ++ 14)

+2

This can be done in C ++ 11 (see @ vasiliy-galkin answer), an example of how this might work for common C / C ++ headers.

C header header, declaring MyEnum.

#ifdef __cplusplus
extern "C" {
#endif

enum MyEnum
#ifdef __cplusplus
: int
#endif
;

#ifdef __cplusplus
}
#endif
0
source

Source: https://habr.com/ru/post/1684340/


All Articles