[英]Redefinition; different basic types (typedef struct)
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?
我相信也许我可能需要在某处使用extern? I've tried experimenting and looking for help on Google, but to no avail.
我尝试过试验并在Google上寻求帮助,但无济于事。
Any help at all would be most appreciated, thank you. 任何帮助都将非常感谢,谢谢。 All four of my files are below.
我的所有四个文件都在下面。
FILE: Foo.h 文件:Foo.h
typedef struct
{
int number;
} my_struct; // Redefinition; different basic types
FILE: Foo.c 文件: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 文件:Bar.h
#include "Foo.h"
void DoSomething(my_struct *number);
FILE: Bar.c 文件:Bar.c
#include "Bar.h"
void DoSomething(my_struct *number)
{
number->number = 10;
}
The problem is you have Foo.h
in Bar.h
. 问题是你在
Foo.h
中有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. 并且
Foo.h
和Bar.h
都包含在main.cpp
,这导致在翻译单元中两次获得my_struct
定义。 Have a ifdef
directive around struct definition file. 在struct定义文件周围有一个
ifdef
指令。 Try this - 试试这个 -
#ifndef FOO_H
#define FOO_H
typedef struct
{
int number;
} my_struct;
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.