aoc-2019/day4/2/neat_macro.h

74 lines
3.3 KiB
C

#ifndef NEAT_MACRO_H
#define NEAT_MACRO_H
#include <stdio.h>
#include <stdlib.h>
/*
* Neat macros for logging
* - bailout: always defined, prints and exits
* - log: defined, except symbol NLOG is defined
* - debug: defined iff symbols DEBUG or TRACE is defined
* - trace: defined iff symbol TRACE is defined
*
* called with (fmt, ...) where fmt is a format string and ... are the
* parameters given to the format string
*/
#define bailout(fmt, ...) \
do { \
fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
exit(EXIT_FAILURE); \
} while (0)
#define log(fmt, ...) \
do { \
fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
#define debug(fmt, ...) \
do { \
if (DEBUG || TRACE) \
fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
#define trace(fmt, ...) \
do { \
if (TRACE) \
fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
/*
* A relaxed alternative to free. Prevents double free'ing errors
* but also hides them.
*/
#define FREE(p) \
do { \
free(p); \
p = NULL; \
} while (0)
/*
* A relaxed alternative to free. Prevents double free'ing errors
* but also hides them.
*/
#define FREE(p) \
do { \
free(p); \
p = NULL; \
} while (0)
/*
* A convenient null check. Bails out if NULL detected
*/
#define NONIL(v) \
do { \
if (v == NULL) { \
bailout(v " is NULL"); \
} \
} while (0)
#endif