Possible to define a function-like macro with a variable body?

后端 未结 4 1796
小鲜肉
小鲜肉 2020-12-18 00:40

I\'ve been looking at the GCC docs for defining macros and it looks like what I want isn\'t possible, but I figure if it is, someone here would know.

What I want to

4条回答
  •  旧时难觅i
    2020-12-18 00:52

    This was the best I came up with:

    #define synchronized(x, things) \
          do { \
               pthread_mutex_t * _lp = &(x); \
               pthread_mutex_lock(_lp);      \
               (things);                     \
               pthread_mutex_unlock(_lp);    \
          } while (0)
    
    ...
    
            synchronized(x,(
                              printf("hey buddy\n"),
                              a += b,
                              printf("bye buddy\n")
                            ));
    

    Note that you have to use the rarely used comma operator and there are restrictions to what code can live within the (not quite java-like) synchronization code list.

提交回复
热议问题