0

So I have some code that is throwing me an error and I am not sure why. I am using a macro to generate myself a string array and an enum that I can use to access the string array in a intuitive way. My compiler is complaining about my macro but the rest of my code seems to work as if the macro successfully created the enum which has me quite confused.

The macro is as follow

#define FOR_EACH_PHASE(PHASE)       \
            PHASE(init)         \
            PHASE(framerate)    \
            PHASE(priority)     \
            PHASE(time)         \
            PHASE(powersave)    \
            PHASE(performance)  \
            PHASE(response)

#define GENERATE_ENUM(ENUM) AI_phase_##ENUM,
#define GENERATE_STRING(STRING) "AI_phase_"#STRING,


typedef enum PHASE_ENUM PHASE_ENUM_t;
enum PHASE_ENUM {
    FOR_EACH_PHASE(GENERATE_ENUM)
    END
};

static const char* PHASE_STRINGS[] = {
    FOR_EACH_PHASE(GENERATE_STRING)
};

Lines such as these seems to compile without error

struct phase_profile* set_defaults;
set_defaults = AI_phases_get_name(PHASE_STRINGS[AI_phase_framerate]);

But the compiler is giving me the following error for each line of my FOR_EACH_PHASE macro

error: 'performance' undeclared (first use in this function)

Any ideas from anyone that knows more about this than me?

Cheers

Alex Hoffmann
  • 355
  • 4
  • 20
  • Why are you using macros? – Ed Heal Sep 28 '17 at 12:50
  • "[...] in a intuitive way" -- no, at least not to me, I find it super hard to understand. If you program in C, please try to program in C, not bend the language into something you like better. – unwind Sep 28 '17 at 13:01
  • I am using macros because the FOR_EACH_PHASE macro is also used to generate other code for each phase. The number of phases and their names etc needs to be modifiable. I could hardcode the enum but would still need the macro @EdHeal – Alex Hoffmann Sep 28 '17 at 13:43
  • How is it hard to understand? each value in the enum has a string name at the same index in the string array as in the enum which allows me to easily get a pointer to the string name and pass to my functions such as AI_phases_get_name which searches a linked list for the data struct with the appropriate name @unwind – Alex Hoffmann Sep 28 '17 at 13:45

1 Answers1

2

I don't have the required reputation to comment so I am posting this as an answer.

I believe you need this:

https://www.codeproject.com/Articles/32000/Improving-C-Enums-Adding-Serialization-Inheritance

I use it for some years now and it is fine!

  • Thanks for the reply. This looks like it is in the right direction but I was hoping to implement something similar to https://stackoverflow.com/questions/9907160/how-to-convert-enum-names-to-string-in-c My code was compiling into a kernel module yesterday but now I am trying to debug some of the more generic code that is not architecture/kernel specific and I am getting a build error on this macro which is confusing me. – Alex Hoffmann Sep 28 '17 at 13:49