Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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;
}
like image 721
Tundra Fizz Avatar asked May 20 '12 03:05

Tundra Fizz


People also ask

What's the difference between struct and typedef?

Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.

Can you redefine typedef?

Using typedef redeclaration, you can redefine a name that is a previous typedef name in the same scope to refer to the same type.

Should structs be typedef?

In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.


1 Answers

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
like image 173
Mahesh Avatar answered Nov 14 '22 04:11

Mahesh