重新定义;不同的基本类型(typedef结构) [英] Redefinition; different basic types (typedef struct)

查看:217
本文介绍了重新定义;不同的基本类型(typedef结构)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在不同文件中定义结构时,尝试使结构正常工作时会遇到麻烦.据我所知,错误告诉我该结构被定义了两次不同的时间.我相信也许我可能需要在某个地方使用extern?我尝试过尝试并在Google上寻求帮助,但无济于事.

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.

文件:Foo.h

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

文件: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);
}

文件:Bar.h

#include "Foo.h"

void DoSomething(my_struct *number);

文件:Bar.c

#include "Bar.h"

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

推荐答案

问题是您在Bar.h中有Foo.h.并且Foo.hBar.h都包含在main.cpp中,这导致两次在翻译单元中获得my_struct定义.在结构定义文件周围有一个ifdef指令.试试这个-

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

这篇关于重新定义;不同的基本类型(typedef结构)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆