thinkerou
thinkerou

Reputation: 1877

How write C macro?

Now I have the follow macro:

#define PHP_FREE_WRAPPED_FUNC_START(name, class_type) \
    void free_##class_type(void *name) { \
        class_type *p = (class_type *)name;
#define PHP_FREE_WRAPPED_FUNC_END() \
        zend_object_std_dtor(&p->std TSRMLS_CC); \
        efree(p); \
    }

Then I want to get free_test1(void *object) function, so I will use:

PHP_FREE_WRAPPED_FUNC_START(object, test1)
    printf("test1\n");
PHP_FREE_WRAPPED_FUNC_END()

And I want to get free_test2(void *object) function, so I will use:

PHP_FREE_WRAPPED_FUNC_START(object, test2)
    printf("test2\n");
PHP_FREE_WRAPPED_FUNC_END() 

But ## can not join free and test1 to get free_test1, why?

Upvotes: 0

Views: 76

Answers (2)

Jesse Chen
Jesse Chen

Reputation: 529

I just simplify your code and ran that, the code you post can work, ## can join the free_ and class_type together.

#define PHP_FREE_WRAPPED_FUNC_START(name, class_type)\
    void free_##class_type(void *name) {\
        printf("%s\n",name);
#define PHP_FREE_WRAPPED_FUNC_END()\
        printf("End\n");\
}\

PHP_FREE_WRAPPED_FUNC_START(hello,test1)
    printf("Middle\n");
PHP_FREE_WRAPPED_FUNC_END()

int main(void)
{
    free_test1("start");
    return 0;
}

And It worked well.

I saw the comments are about the backslash. I guess you have fixed the error.

Upvotes: 1

Your problem is that the C++ style comments you are using (//) comment out the line continuation (\) needed for the macro. You can solve this by either moving the comments outside of the macro definition, or by using C style comments (/* */), like that:

#define FUNC_END() \
    /* common end code */
}

But for such small macros, you probably don't even need to use two lines:

// common end code
#define FUNC_END() }

Upvotes: 1

Related Questions