C语言 重复代码的分离 - common.h 文件 - 使用自定义参数声明函数



>假设我有文件A.c和文件B.c,我想将公共代码移动到common.h和common.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(来自BC(移动到那里。 但这并不能解决我的问题。第二个标头中的 STRUCT 版本将涵盖第一个标头中的版本。

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。

最新更新