C macro issue: redefinition of functions / structure

Posted by Andrei Ciobanu on Stack Overflow See other posts from Stack Overflow or by Andrei Ciobanu
Published on 2010-06-08T21:28:00Z Indexed on 2010/06/08 21:32 UTC
Read the original article Hit count: 173

Filed under:
|
|
|

Given the following code (it's a macro that generates code for a list data structure, based on the contained type).

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 */

And here is how the above code works:

#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);
}

My question, is it possible to somehow be able to call : LIST_TEMPLATE_INIT(int), as many times as I want, in a decentralized fashion ?

The current issue with this right now is that calling LIST_TEMPLATE_INIT(int) in another file raise compilation errors (because of function redefinition):

Example of error:

error: redefinition of ‘struct __list_s_int’

© Stack Overflow or respective owner

Related posts about c

    Related posts about macros