Created
September 16, 2022 17:13
-
-
Save BlackGoku36/17b5b2d4218c8c677d2f79757cdff838 to your computer and use it in GitHub Desktop.
A small debug print header
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
/* | |
Small debug print header file inspired from book 'Learn C the Hard Way' | |
Usage: | |
- To use `dbg_debug()`, add -DDBG as compiler flag | |
- `dbg_info`, `dbg_warn`, `dbg_error` is for logging | |
- `dbg_test(EXPR, MESSAGE, ...)` tests EXPR, if not true, then it print MESSAGE and jump to label `error`, | |
where you can handle the failed test. | |
- `dbg_test_panic(EXPR, MESSAGE, ...)` tests EXPR, if not true, then it print MESSAGE and aborts. | |
- Example code: | |
#include "dbg.h" | |
int main(int argc, char* argv[]){ | |
int x = 5; | |
int y = 5; | |
dbg_test(x == y, "X == Y"); // jumps to error label if x != y | |
dbg_debug("X: %d, Y: %d", 5, 5); | |
dbg_info("Some information%c", '!'); | |
dbg_warn("WARNINGIN!"); | |
dbg_error("*(^*&435GUYGUG&^$^YTFG564&!"); | |
dbg_test_panic(x == y, "hmmmmmm"); // aborts if x != y | |
return 0; | |
error: | |
fprintf(stderr, "Oh dear\n"); | |
return -1; | |
} | |
*/ | |
#ifndef DBG_H | |
#define DBG_H | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#ifdef DBG | |
#define dbg_debug(M, ...) fprintf(stderr, "[DEBUG]:\n %s: %s: %d: " M "\n",\ | |
__FILE__, __func__, __LINE__, ##__VA_ARGS__) | |
#else | |
#define dbg_debug(M, ...) | |
#endif | |
#define get_error_str() (errno == 0 ? "NONE" : strerror(errno)) | |
#define blue(M) "\033[96m" M "\033[0m" | |
#define yellow(M) "\033[93m" M "\033[0m" | |
#define red(M) "\033[31m" M "\033[0m" | |
#define dbg_info(M, ...) fprintf(stderr, blue("[INFO]") ":\n %s: %s: %d: " M "\n",\ | |
__FILE__, __func__, __LINE__, ##__VA_ARGS__) | |
#define dbg_warn(M, ...) fprintf(stderr, yellow("[WARN, ERRNO: %s]") ":\n %s: %s: %d: " M "\n",\ | |
get_error_str(), __FILE__, __func__, __LINE__, ##__VA_ARGS__) | |
#define dbg_error(M, ...) fprintf(stderr, red("[ERROR, ERRNO: %s]") ":\n %s: %s: %d: " M "\n",\ | |
get_error_str(), __FILE__, __func__, __LINE__, ##__VA_ARGS__) | |
#define dbg_test(B, M, ...) if(!(B)){\ | |
fprintf(stderr, red("[TEST] '" #B "' failed") ":\n %s: %s: %d: " M "\n",\ | |
__FILE__, __func__, __LINE__, ##__VA_ARGS__); errno = 0; goto error;} | |
#define dbg_test_panic(B, M, ...) if(!(B)){\ | |
fprintf(stderr, red("[TEST PANIC] '" #B "' failed") ":\n %s: %s: %d: " M "\n",\ | |
__FILE__, __func__, __LINE__, ##__VA_ARGS__); abort();} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment