请注意,有几个关于 SO 循环依赖的问题(包括我自己问过的一个问题),但我觉得它们都没有帮助我解决这个特定问题。
请考虑以下两个文件:
表.h
#ifndef s_table_h
#define s_table_h
#include "value.h"
#include "object.h"
typedef struct {
ObjectString* key;
Value value;
} Entry;
typedef struct {
int capacity;
int count;
Entry* entries;
} Table;
void initTable(Table* table);
void setTable(Table* table, ObjectString* key, Value value);
bool getTable(Table* table, ObjectString* key, Value* out);
#endif
object.h
#ifndef s_object_h
#define s_object_h
#include "common.h"
#include "table.h"
typedef enum {
OBJECT_STRING
} ObjectType;
typedef struct {
ObjectType type;
Table attributes;
} Object;
typedef struct {
Object base;
char* chars;
int length;
} ObjectString;
bool stringsEqual(ObjectString* a, ObjectString* b);
#endif
如您所见,这两个相互依赖:table.h
需要 ObjectString*
,而 object.h
需要一个具体的表
。两个相应的 .c
实现文件分别访问 ObjectString*
和 Table
的具体成员。
解决这个问题的推荐方法是什么?一般来说,用 C 语言解决此类问题的常用方法是什么?
请纯粹解决技术方面的问题,而不是软件设计方面的问题。
最佳答案
我想您可能会说我在这里解决的是软件设计方面的问题,但我不知道如何在不稍微重构代码的情况下做到这一点。即,暂时避免使用 typedef。 (尽管我建议永久转储 typedef。)对于您的特定情况,table.h 不需要知道 ObjectString 是什么,因为它只使用指向它的指针。所以你可以简单地不在table.h中导入“object.h”,而是写:
对象.h:
#ifndef s_object_h
#define s_object_h
#include "common.h"
#include "table.h"
typedef enum {
OBJECT_STRING
} ObjectType;
typedef struct {
ObjectType type;
Table attributes;
} Object;
struct ObjectString {
Object base;
char* chars;
int length;
};
typedef struct ObjectString ObjectString;
bool stringsEqual(ObjectString* a, ObjectString* b);
#endif
表.h:
#ifndef s_table_h
#define s_table_h
#include "value.h"
typedef struct {
struct ObjectString* key;
Value value;
} Entry;
typedef struct {
int capacity;
int count;
Entry* entries;
} Table;
void initTable(Table* table);
void setTable(Table* table, struct ObjectString* key, Value value);
bool getTable(Table* table, struct ObjectString* key, Value* out);
#endif
关于c - 如何解决头文件之间的这种相互依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978498/