C:重新定义“结构" [英] C : redefinition of ‘struct'
问题描述
我在重新定义结构体时遇到了麻烦.为了解释我的问题,我将考虑 4 个文件.
I'm in trouble with the Warning redefinition of struct. To explain my problem I will consider 4 files.
- 接口.c
- 解析器.h
- Auth.h
- 信息.h
Interface.c
#include "Auth.h"
#include "Info.h"
/* some code here */
解析器.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 */
当我在 Interface.c 中不包含 Info.h 或 Auth.h 时,没有问题.
When I don't include Info.h or Auth.h in Interface.c there is no problem.
推荐答案
你需要添加一个保护来防止 Parser.h 被包含两次,就像这样:
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
因为每次编写指令 #include "Parser.h"
时,Parser.h 的内容都会简单地复制粘贴到包含位置.这意味着您将同时声明两个结构.
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.
使用 ifndef
可以防止它被多次复制粘贴.
With the ifndef
you prevent it from being copy-pasted more than once.
这篇关于C:重新定义“结构"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!