假设我有文件 A.c 和文件 B.c,我想将通用代码移动到 common.h 和 common.c 文件。
文件 A.c
typedef struct mystruct {
long long nameA; <--- different member
struct astruct *next;
} MYSTRUC;
void free_table(MYSTRUC** tab) { <--- same code in A.c and B.c
int i;
MYSTRUC* current;
MYSTRUC* tmp;
for (i = 0; i < TSIZE; i++) {
current = tab[i];
while (current != NULL) {
tmp = current;
current = current->next;
free(tmp);
}
}
free(tab);
}
MYSTRUC** inittable() {
int i;
MYSTRUC **tab;
ht = (MYSTRUC**) malloc( sizeof(MYSTRUC*) * TSIZE );
for (i = 0; i < TSIZE; i++) tab[i] = (MYSTRUC*) NULL;
return tab;
}
void otherA2() {uses nameA}
文件 B.c
typedef struct mystruct {
long long nameB; <---- different member
struct bstruct *next;
} MYSTRUC;
void free_table(MYSTRUC** tab) { <--- same code in A.c and B.c
int i;
MYSTRUC* current;
MYSTRUC* tmp;
for (i = 0; i < TSIZE; i++) {
current = tab[i];
while (current != NULL) {
tmp = current;
current = current->next;
free(tmp);
}
}
free(tab);
}
MYSTRUC** inittable() {
int i;
MYSTRUC **tab;
ht = (MYSTRUC**) malloc( sizeof(MYSTRUC*) * TSIZE );
for (i = 0; i < TSIZE; i++) tab[i] = (MYSTRUC*) NULL;
return tab;
}
void otherB2() {uses nameB}
如果我在 common.h 中放置 free_table() 声明,编译器将提示未知类型 MYSTRUC。我可以创建文件 A.h 和 B.h 并将其移至 MYSTRUC(来自 A.c)和 MYSTRUC(来自 B.c)。 但这并不能解决我的问题。第二个 header 中的 STRUCT 版本将覆盖第一个 header 中的版本。
File common.h
#include "A.h" <--- wrong
#include "B.h" <--- wrong
void free_table(MYSTRUC** str){ <--- same code in A.c and B.c
....
}
遇到这种情况我该如何解决?没有模板可以做到吗?
最佳答案
根据评论中的讨论,我明白我想要得到的是函数重载。我将分离不依赖于自定义类型 (MYSTRUC) 的函数,并将 free_table() 和 init_table() 保留在当前形式中。
谢谢@klutt、@Fire Lancer、@WhozCraig。
关于c - 重复代码的分离 - common.h 文件 - 带有自定义参数的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59837325/