Make enums defined inside C ++ structures have global scope

The following code will compile as C, but not as C ++:

#include <stdio.h>

struct somestruct {
    int id;
    enum {
        STATE1 = 0,
        STATE2,
        STATE3,
        STATE4,
    } state;
};

int main(int argc, char *argv[])
{
    static struct somestruct s;

    if (s.state == STATE1) {
        printf("state1\n");
    }

    return 0;
}

In C ++, I would have to use somestruct::STATE1(because enum declaration is limited by structure / class?). The project I'm working on should be written in C, but we are currently using some C ++ libraries (Arduino), so we compile our c-code using the C ++ compiler. So, is there a way to make the code above in C ++?

+4
source share
4 answers

You can encode it in a form compatible with both languages, for example:

typedef enum 
{
    STATE1 = 0,
    STATE2,
    STATE3,
    STATE4,
} eState ;

struct somestruct 
{
    int id ;
    eState state ;
};

, , ( ) , , ( ):

#if defined __cplusplus
    #define SOMESTRUCT(e) somestruct:: e
#else
    #define SOMESTRUCT(e) e
#endif

:

...
    if (s.state == SOMESTRUCT(STATE1)) {
...
+3

using, :

struct somestruct {
    int id;
    enum {
        STATE1 = 0,
        STATE2,
        STATE3,
        STATE4,
    } state;
};

#ifdef __cplusplus
using somestruct::STATE1; // <-- here
#endif
+1

++ , , : somestruct::STATE1.

, , , . somestruct::STATE1 ++ STATE1 C. , .

s->state; s .

0
source

You can use the macro definition c

#define STATE1 somestruct::STATE1

This should allow STATE1 to go. I would recommend against it, since you are using the C ++ compiler so that you can use the C ++ features it gives you, and just put somestruct :: STATE1.

-2
source

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


All Articles