Skip to content

Instantly share code, notes, and snippets.

@dafrancis
Created November 14, 2011 21:29
Show Gist options
  • Save dafrancis/1365246 to your computer and use it in GitHub Desktop.
Save dafrancis/1365246 to your computer and use it in GitHub Desktop.
"Zed's Awesome Debug Macros" from Exercise 20 of "Learn C the Hard Way" (http://c.learncodethehardway.org/). Now with added colours! (Yes I know I use "color" in the code)
#ifndef __color_h__
#define __color_h__
/*
* I got some of the colour codes (as well as having the idea of putting them in a macro) from here:
* http://stackoverflow.com/questions/3506504/c-code-changes-terminal-text-color-how-to-restore-defaults-linux
*/
#define RED "\e[31m"
#define GREEN "\e[32m"
#define YELLOW "\e[33m"
#define WHITE "\e[1m"
/*
* COLOR_X resets the colour. Yes I'm inconsistent with how I spell colour.
*/
#define COLOR_X "\e[m"
#endif
#ifndef __dbg_h__
#define __dbg_h__
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "color.h"
#ifdef NDEBUG
#define debug(M, ...)
#else
#define debug(M, ...) fprintf(stderr, "DEBUG %s:%d:%s: " M "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#endif
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_err(M, ...) fprintf(stderr, RED "[ERROR]" COLOR_X " (%s:%d:%s: errno: %s) " M "\n", __FILE__, __LINE__, __func__, clean_errno(), ##__VA_ARGS__)
#define log_warn(M, ...) fprintf(stderr, YELLOW "[WARN]" COLOR_X " (%s:%d:%s: errno: %s) " M "\n", __FILE__, __LINE__, __func__, clean_errno(), ##__VA_ARGS__)
#define log_info(M, ...) fprintf(stderr, WHITE "[INFO]" COLOR_X " (%s:%d:%s) " M "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }
#define sentinel(M, ...) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }
#define check_mem(A) check((A), "Out of memory.")
#define check_debug(A, M, ...) if(!(A)) { debug(M, ##__VA_ARGS__); errno=0; goto error; }
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment