c语言实现defer
#define __DEFER_CONCAT_IMPL__(s1, s2) s1##_##s2
#define __DEFER_CONCAT__(s1, s2) __DEFER_CONCAT_IMPL__(s1, s2)
#if defined(__clang__)
static inline void __defer_cleanup__(void (^*b)(void)) { (*b)(); }
#define DEFER(expr) __attribute__((cleanup(__defer_cleanup__))) void (^__DEFER_CONCAT__(_DEFER_VAR_, __LINE__))(void) = ^{ expr; }
#elif defined(__GNUC__)
#define DEFER(expr) \
void __DEFER_CONCAT__(_DEFER_FUNC_, __LINE__)() { expr; } \
int __DEFER_CONCAT__(_DEFER_VAR_, __LINE__) __attribute__((cleanup(__DEFER_CONCAT__(_DEFER_FUNC_, __LINE__))))
#else
#error "platform not support!"
#endif
#include <stdio.h>
int main(int argc, char **argv)
{
#if defined(__clang__)
printf("clang\n");
#elif defined(__GNUC__)
printf("GNUC\n");
#else
printf("other\n");
#endif
{
printf("begin of scope\n");
DEFER(printf("call defer1\n"));
DEFER(printf("call defer2\n"));
printf("end of scope\n");
}
printf("before return\n");
return 0;
printf("after return\n");
}
gcc test.c -o test && ./test
clang -g -fblocks test.c -o test -lBlocksRuntime && ./test