Can I 'extend' a struct in C?

后端 未结 7 1466
太阳男子
太阳男子 2020-12-08 16:05
typedef struct foo_s {
    int a;
} foo;

typedef struct bar_s {
    foo;
    int b;
} bar;

Essentially I want to do:

bar b;
b.a;
<         


        
7条回答
  •  -上瘾入骨i
    2020-12-08 16:46

    It can be easily done via preprocessor:

    Create a file named base_foo.h:

    int foo;
    

    Then simply include it:

    typedef struct foo_s {
        #include "base_foo.h"
    } foo;
    
    typedef struct bar_s {
        #include "base_foo.h"
        int b;
    } bar;
    

提交回复
热议问题