*a
: value of a
&a
: address of a
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <stdio.h> #include <stdlib.h>
typedef struct object Object; typedef int (*func_t)(Object *);
struct object { int a, b; func_t add, sub; };
static int add_impl(Object *self) { return self->a + self->b; } static int sub_impl(Object *self) { return self->a - self->b; }
int init_object(Object **self)
{ if (NULL == (*self = malloc(sizeof(Object)))) return -1; (*self)->a = 0; (*self)->b = 0; (*self)->add = add_impl; (*self)->sub = sub_impl;
return 0; }
int main(int argc, char *argv[])
{ Object *o = NULL; init_object(&o); o->a = 9922; o->b = 5566; printf("add = %d, sub = %d\n", o->add(o), o->sub(o)); return 0; }
|
1
| typedef int (*func_t)(Object *);
|
Stringfication and concatenation
考慮以下MACRO -object.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #ifndef __RAY_OBJECTS_H #define __RAY_OBJECTS_H
#define DECLARE_OBJECT(name) \ struct __##name##_node; \ typedef struct __##name##_node *name##_node; \ struct __##name##_node { \ name element; \ name##_node next; \ }; \ void append_##name(const name *X, name##_node *list); \ void delete_##name##_list(name##_node *list);
DECLARE_OBJECT(light) DECLARE_OBJECT(rectangular) DECLARE_OBJECT(sphere)
#undef DECLARE_OBJECT
#endif
|
light
在DECLARE_OBJECT(light)
中會取代name,故會產生以下
1
| struct __light_node; typedef struct __light_node *light_node; struct __light_node { light element; light_node next; }; void append_light(const light *X, light_node *list); void delete_light_list(light_node *list);
|
故對object.c
前處理後(gcc -E -P source.c
)
1 2 3
| struct __light_node; typedef struct __light_node *light_node; struct __light_node { light element; light_node next; }; void append_light(const light *X, light_node *list); void delete_light_list(light_node *list); struct __rectangular_node; typedef struct __rectangular_node *rectangular_node; struct __rectangular_node { rectangular element; rectangular_node next; }; void append_rectangular(const rectangular *X, rectangular_node *list); void delete_rectangular_list(rectangular_node *list); struct __sphere_node; typedef struct __sphere_node *sphere_node; struct __sphere_node { sphere element; sphere_node next; }; void append_sphere(const sphere *X, sphere_node *list); void delete_sphere_list(sphere_node *list);
|