redefinition of typedef

前端 未结 7 922
北荒
北荒 2020-12-15 05:54

I am possibly doing this incorrectly and this is much a question about why it works in one compiler and not the other.

I have a large C application, and I am

7条回答
  •  囚心锁ツ
    2020-12-15 06:15

    You are defining multiple times the same thing.

    You can spread it across multiple header files just have to make sure that there is some B seen before struct _A is defined.

    This code works:

    #include 
    
    typedef struct _B B;
    typedef struct _A A;
    
    struct _A {
        double a;
        B *b;
    };
    
    struct _B {
        int c;
    };
    
    void function_do_something(A* a, B* b)
    {
        printf("a->a (%f) b->c (%d)\n", a->a, b->c);
    }
    
    int main()
    {
       A a;
       B b;
    
      a.a = 3.4;
      b.c = 34;
    
      function_do_something(&a, &b);
    
      return 0;
    }
    

    Output:

    > ./x
    a->a (3.400000) b->c (34)
    

    EDIT: updated for C

    EDIT 2: spread into multiple header files

    b.h:

    #ifndef B_H
    #define B_H
    
    struct _B {
        int c;
    };
    
    #endif
    

    a.h:

    #ifndef A_H
    #define A_H
    
    typedef struct _B B;
    
    struct _A {
        double a;
        B *b;
    };
    
    typedef struct _A A;
    
    #endif
    

    main.c:

    #include 
    
    #include "a.h"
    #include "b.h"
    
    void function_do_something(A* a, B* b)
    {
        printf("a->a (%f) b->c (%d)\n", a->a, b->c);
    }
    
    int main()
    {
       A a;
       B b;
    
      a.a = 3.4;
      b.c = 34; 
    
      function_do_something(&a, &b);
    
      return 0;
    }
    

提交回复
热议问题