Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : redefinition of ‘struct' [duplicate]

Tags:

c

struct

I'm in trouble with the Warning redefinition of struct. To explain my problem I will consider 4 files.

  • Interface.c
  • Parser.h
  • Auth.h
  • Info.h

Interface.c

    #include "Auth.h"
    #include "Info.h"

/* some code here */

Parser.h

struct ParsedAuthResponse {
   char *name;
   char *key;
};

struct ParsedInfoResponse {
   char *name;
   char *message;
};
void auth_parser(char* serverResponse,struct ParsedAuthResponse *response_a);
void scrobble_parser(char* serverResponse, int* scrobbleParsedparsedResponse);
void love_unlove_parser(char* serverResponse, int* loveUnloveParsedResponse);
void getInfo_parser(char* serverResponse,struct ParsedInfoResponse *responseP);

Auth.h

#include "parser.h"
functionX(int a, struct ParsedAuthResponse *response);
/* some code here */

Info.h

#include "parser.h"
functionY(int a, struct ParsedInfoResponse *response);
/* some code here */

When I don't include Info.h or Auth.h in Interface.c there is no problem.

like image 737
W.draoui Avatar asked Oct 21 '25 15:10

W.draoui


2 Answers

You need to add a guard that prevents Parser.h to be included twice, like this :

#ifndef PARSER_H
#define PARSER_H
struct ParsedAuthResponse {
   char *name;
   char *key;
};

struct ParsedInfoResponse {
   char *name;
   char *message;
};
void auth_parser(char* serverResponse,struct ParsedAuthResponse *response_a);
void scrobble_parser(char* serverResponse, int* scrobbleParsedparsedResponse);
void love_unlove_parser(char* serverResponse, int* loveUnloveParsedResponse);
void getInfo_parser(char* serverResponse,struct ParsedInfoResponse *responseP);
#endif

Because each time you write the instruction #include "Parser.h" the content of Parser.h will simply be copy-pasted at the include location. This means that you will have both structures declared twice.

With the ifndef you prevent it from being copy-pasted more than once.

like image 192
Tim Avatar answered Oct 23 '25 05:10

Tim


The problem here is that during compilation, interface.c + all its included headers form a "translation unit". But since two of the headers both include parser.h, it will appear as if the contents in that header is declared twice.

To avoid problems like these, you should always use so-called "header guards" in every single header file you write:

#ifndef PARSER_H  // header guard
#define PARSER_H

struct ParsedAuthResponse {
   char *name;
   char *key;
};

struct ParsedInfoResponse {
   char *name;
   char *message;
};

...

#endif // PARSER_H

This ensures that the contents are only visible once per translation unit.

like image 35
Lundin Avatar answered Oct 23 '25 03:10

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!