cenumstypedef

How to typedef one enum type to another?


Here's a minimal example of what I'm trying to do:

enum color { RED, GREEN, BLUE };
typedef enum legacy_color enum color;

int
main(void)
{
    return 0;
}

Compilation fails with

test.c:13:27: error: two or more data types in declaration specifiers
   13 | typedef enum legacy_color enum color;
      |                           ^~~~
test.c:13:32: warning: empty declaration with storage class specifier does not redeclare tag
   13 | typedef enum legacy_color enum color;
      |                                ^~~~~

Motivation: I need to rename an enum to align with current naming conventions in my project. The old name needs to remain as an alias, which will be declared in a compatibility header file. Referring back to my example, enum color { RED, GREEN, BLUE } will be in the main header file, and typedef enum legacy_color enum color would go in the backward-compatibility header file.

The only other approach I've been able to come up with is #define legacy_color color, but that's overly broad and would match outside the enum type context.

Note that typedef enum color legacy_color; is not acceptable, because the type has changed from enum legacy_color to simply legacy_color.


Solution

  • Apart from macros, which are risky in this context, there's no way to do this. No way to alias just an enum tag (actually, there's no enum tags, just tags, and the tag namespace is shared between enums, structs and unions, meaning enum foo conflicts with struct foo and/or union foo but not a plain name foo (variable name or type name; doesn't matter)).

    If you want to communicate that a type alias is an enum, you can put the word enum in the type alias's name, e.g., typedef enum legacy_color enum_color;.