Apr 20, 2010 at 10:04pm UTC
Hello.
Many times I find the use of #define preprocessor macro to define type/data strctures, but I haven't unsertood very well its syntax. As an example here is anexcerpt from object.h from Python sources:
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_EXTRA_INIT 0, 0,
#else
#define _PyObject_HEAD_EXTRA
#define _PyObject_EXTRA_INIT
#endif
/* PyObject_HEAD defines the initial segment of every PyObject. */
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
Py_ssize_t ob_refcnt; \
struct _typeobject *ob_type;
#define PyObject_HEAD_INIT(type) \
_PyObject_EXTRA_INIT \
1, type,
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
Questions:
1 - how the commas are interpreted?
2 - how the expansion works in these cases?
(3 - what's the gain respect to using typedef?)
thanks a lot!
giovanni
Apr 21, 2010 at 12:28am UTC
#define is essentially a search-and-replace. Anywhere _PyObject_HEAD_EXTRA
is found, replace it verbatim with the text that follows.
#define has more uses than what typedef has. #define should not be used
when typedef could be.
Apr 21, 2010 at 9:20am UTC
thanks jsmith.
So the define explands to a literal replacement. So the following defines
#define _PyObject_EXTRA_INIT 0, 0,
#define PyObject_HEAD_INIT(type) \
_PyObject_EXTRA_INIT \
1, type,
make the following expand to
static PyTypeObject SimpleObjectType = {
************
PyObject_HEAD_INIT(NULL)
************
/*expands to*/
************
0,
0,
1,
NULL,
************
etc.
};
right?
(I don't know this way of defining a type, using curly braces, but this is another question...)
Apr 21, 2010 at 9:46am UTC
Many things to learn: this is a simple structure initialization... now everything is clear.