给出下面的代码(它是为一个列表数据结构生成代码的宏的基础上,包含的类型)。
list.h
#ifndef _LIST_H
#define _LIST_H
#ifdef __cplusplus
extern "C" {
#endif
#define LIST_TEMPLATE_INIT(type) \
typedef struct __list_s_##type { \
struct __list_s_##type *next; \
type value; \
} __list_##type; \
\
__list_##type * __list_##type##_malloc(type value){ \
__list_##type * list = NULL; \
list = malloc(sizeof(*list)); \
list->value = value; \
return list; \
}\
\
void __list_##type##_free(__list_##type *list){\
__list_##type * back = list;\
while(list=list->next){\
free(back);\
back = list;\
}\
}
#define LIST_TYPE(type) __list_##type
#define LIST_MALLOC(type,value) __list_##type##_malloc(value)
#define LIST_FREE(type,list) __list_##type##_free(list)
#define LIST_DATA(list) (list->value)
#ifdef __cplusplus
}
#endif
#endif /* _LIST_H */
这里是上面的代码是如何工作的:
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
/*
*
*/
LIST_TEMPLATE_INIT(int)
int main(int argc, char** argv)
{
LIST_TYPE(int)* list = NULL;
list = LIST_MALLOC(int, 5);
printf("%d",LIST_DATA(list));
LIST_FREE(int,list);
return (0);
}
我的问题,是有可能以某种方式能够调用: LIST_TEMPLATE_INIT(int)
很多次,因为我想,以分散的方式?
与现在这个权利目前的问题是,调用LIST_TEMPLATE_INIT(int)
在另一个文件中加注编译错误(因为重新定义函数):
误差的例子:
error: redefinition of ‘struct __list_s_int’
error: redefinition of ‘struct __list_s_int’
error: conflicting types for ‘__list_int’
note: previous declaration of ‘__list_int’ was here
error: conflicting types for ‘__list_int_malloc’
note: previous definition of ‘__list_int_malloc’ was here
error: conflicting types for ‘__list_int_free’
note: previous definition of ‘__list_int_free’ was here