Last active
July 3, 2021 05:18
-
-
Save glapa-grossklag/12063809f05ecc592e8efaf59c6cda54 to your computer and use it in GitHub Desktop.
Some C debug macros
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A collection of three macros for debugging: DEBUG, WARN, ERROR. | |
* | |
* All three take a variable number of arguments and match the format of the | |
* printf family of functions. For example: | |
* WARN("The value of n is %d\n", n); | |
* | |
* All three are disabled if NDEBUG is defined, just like assert. | |
* | |
* by Miles Glapa-Grossklag, 2021 | |
*/ | |
#ifndef DEBUG_H | |
#define DEBUG_H | |
#include <stdarg.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
// Begin an escape sequence. | |
#define _DEBUG_COLOR "\033[" | |
// End an escape sequence. | |
#define _DEBUG_END "m" | |
#define _DEBUG_RESET "0" | |
#define _DEBUG_RED "91" | |
#define _DEBUG_GREEN "92" | |
#define _DEBUG_YELLOW "93" | |
#ifdef NDEBUG | |
// If NDEBUG is defined, the macros should do nothing. | |
#define DEBUG(...) ((void)((__VA_ARGS__)) | |
#define WARN(...) ((void)((__VA_ARGS__)) | |
#define ERROR(...) ((void)((__VA_ARGS__)) | |
#else | |
#define DEBUG(...) \ | |
do { \ | |
fprintf(stderr, _DEBUG_COLOR _DEBUG_GREEN _DEBUG_END \ | |
"[DEBUG]" _DEBUG_COLOR _DEBUG_RESET _DEBUG_END " "); \ | |
fprintf(stderr, __VA_ARGS__); \ | |
} while (0) | |
#define WARN(...) \ | |
do { \ | |
fprintf(stderr, _DEBUG_COLOR _DEBUG_YELLOW _DEBUG_END \ | |
"[WARNING]" _DEBUG_COLOR _DEBUG_RESET _DEBUG_END " "); \ | |
fprintf(stderr, __VA_ARGS__); \ | |
} while (0) | |
#define ERROR(...) \ | |
do { \ | |
fprintf(stderr, _DEBUG_COLOR _DEBUG_RED _DEBUG_END \ | |
"[ERROR]" _DEBUG_COLOR _DEBUG_RESET _DEBUG_END " "); \ | |
fprintf(stderr, __VA_ARGS__); \ | |
} while (0) | |
#endif | |
#endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "debug.h" | |
int main(void) { | |
DEBUG("I'm some debug info\n"); | |
WARN("I'm a warning\n"); | |
ERROR("I'm an error!\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment