Redefinition; different basic types (typedef struct)

一世执手 提交于 2019-12-13 11:58:03

问题


I'm having a bit of trouble trying to get structs to work properly when they are defined in different files. From as far as I can tell, the error is telling me that the struct is being defined two different times. I believe that perhaps I may need to use extern somewhere? I've tried experimenting and looking for help on Google, but to no avail.

Any help at all would be most appreciated, thank you. All four of my files are below.

FILE: Foo.h

typedef struct
{
    int number;
} my_struct;    // Redefinition; different basic types

FILE: Foo.c

#include "Foo.h"
#include "Bar.h"
#include <stdio.h>

my_struct test;

int main(void)
{
    test.number = 0;
    DoSomething(&test);
    printf("Number is: ", &test.number);
}

FILE: Bar.h

#include "Foo.h"

void DoSomething(my_struct *number);

FILE: Bar.c

#include "Bar.h"

void DoSomething(my_struct *number)
{
    number->number = 10;
}

回答1:


The problem is you have Foo.h in Bar.h. And both Foo.h and Bar.h are being included in main.cpp, which results getting the my_struct definition twice in the translation unit. Have a ifdef directive around struct definition file. Try this -

#ifndef FOO_H
#define FOO_H

  typedef struct
  {
      int number;
  } my_struct;    

#endif


来源:https://stackoverflow.com/questions/10670596/redefinition-different-basic-types-typedef-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!