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

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

Using the cleanup variable attribute in GCC

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

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

posted @ 2023-06-20 02:54  Tifa_Best  阅读(117)  评论(0编辑  收藏  举报