solidc
Robust collection of general-purpose cross-platform C libraries and data structures designed for rapid and safe development in C
Loading...
Searching...
No Matches
defer.h File Reference

Cross-platform defer statement implementation for automatic resource cleanup. This header provides a 'defer' statement that executes code when the current scope exits, similar to Go's defer or other languages' scope guards. More...

#include <stddef.h>
Include dependency graph for defer.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Detailed Description

Cross-platform defer statement implementation for automatic resource cleanup. This header provides a 'defer' statement that executes code when the current scope exits, similar to Go's defer or other languages' scope guards.

References:

Compilation Instructions

C++: g++ main.cpp clang++ main.cpp cl main.cpp (MSVC) No special flags required - uses RAII with lambdas

C with GCC: gcc -fno-trampolines main.c Uses function descriptors (safe, no executable stack required)

Alternative for GCC 4.9+: gcc main.c Uses nested functions with auto storage class (safe, no trampolines)

C with Clang: clang -fblocks -lBlocksRuntime main.c Requires blocks runtime library

Install blocks runtime: Ubuntu/Debian: sudo apt-get install libblocksruntime-dev Arch Linux: sudo pacman -S libdispatch

C with MSVC: cl main.c Uses __try/__finally (no special flags required)

Usage Example

#include "defer.h"
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f = fopen("test.txt", "w");
defer({ fclose(f); printf("File closed\n"); });
void *ptr = malloc(100);
defer({ free(ptr); printf("Memory freed\n"); });
fprintf(f, "Hello, World!\n");
// Cleanup happens automatically in reverse order
return 0;
}
Cross-platform defer statement implementation for automatic resource cleanup. This header provides a ...

Definition in file defer.h.