c语言实现defer

发布时间 2023-06-20 03:00:17作者: Tifa_Best
#define __DEFER_CONCAT_IMPL__(s1, s2) s1##_##s2
#define __DEFER_CONCAT__(s1, s2) __DEFER_CONCAT_IMPL__(s1, s2)

#if defined(__llvm__)
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(__llvm__)
    printf("llvm\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

您需要使用块链接哪些库来进行clang程序

Using the cleanup variable attribute in GCC

defer 关键字在 C/C++ 上的实现方案

Emulating "defer" in C, with Clang or GCC+Blocks