通过宏定义控制debug打印
# 通过宏定义控制debug打印
参考: https://github.com/bytebutt/c-debug-header.git (opens new window)
包含头文件debug_print.h
#pragma once
#include <stdio.h>
#include <string.h>
#ifdef DEBUG_LEVEL_INFO
# define DEBUG_LEVEL_WARNING
# define DEBUG_LEVEL_ERROR
#endif
#ifdef DEBUG_LEVEL_WARNING
# define DEBUG_LEVEL_ERROR
#endif
#define DEBUG_COLOR_RED "\033[31m"
#define DEBUG_COLOR_GREEN "\033[32m"
#define DEBUG_COLOR_YELLOW "\033[33m"
#define DEBUG_COLOR_BLUE "\033[34m"
#define DEBUG_COLOR_PURPLE "\033[35m"
#define DEBUG_COLOR_RESET "\033[m"
#define filename_strip_path(x) strrchr(x,'/')?strrchr(x,'/')+1:x
#define debug_prefix(tag,color) printf(color "[%s|%d|%s]: " tag DEBUG_COLOR_RESET, filename_strip_path(__FILE__), __LINE__, __func__)
#if defined(DEBUG_LEVEL_INFO)
# define debug_info(...) do { debug_prefix("DEBUG_INFO: ", DEBUG_COLOR_RESET); printf(__VA_ARGS__); printf("\n"); } while(0)
#else
# define debug_info(...) ((void) 0)
#endif
#ifdef DEBUG_LEVEL_WARNING
# define debug_warning(...) do { debug_prefix("DEBUG_WARNING: ", DEBUG_COLOR_YELLOW); printf(__VA_ARGS__); printf("\n"); } while(0)
#else
# define debug_warning(...) ((void) 0)
#endif
#ifdef DEBUG_LEVEL_ERROR
# define debug_error(...) do { debug_prefix("DEBUG_ERROR: ", DEBUG_COLOR_RED); printf(__VA_ARGS__); printf("\n"); } while(0)
# define debug_assert(expr) do { if (!(expr)) { debug_prefix("ASSERTION FAILED: ", DEBUG_COLOR_PURPLE); printf(#expr); printf("\n"); } } while(0)
#else
# define debug_error(...) ((void) 0)
# define debug_assert(...) ((void) 0)
#endif
#define print_info(...) do { debug_prefix("PRINT_INFO: ", DEBUG_COLOR_GREEN); printf(__VA_ARGS__); printf("\n"); } while(0)
#define print_warning(...) do { debug_prefix("PRINT_WARNING: ", DEBUG_COLOR_YELLOW); printf(__VA_ARGS__); printf("\n"); } while(0)
#define print_error(...) do { debug_prefix("PRINT_ERROR: ", DEBUG_COLOR_RED); printf(__VA_ARGS__); printf("\n"); } while(0)
#define error_exit(...) do { debug_prefix("ERROR_EXIT: ", DEBUG_COLOR_RED); printf(__VA_ARGS__); printf(" - %s\n", strerror(errno)); exit(errno);} while(0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
使用:
// #define DEBUG_INFO
#define DEBUG_WARNING
debug_info("this is a info\n");
debug_warning("this is a warning\n");
print_warning("this is a warning, will always print\n");
1
2
3
4
5
6
7
2
3
4
5
6
7
# 宏定义转字符串
#define _MACRO_TO_STR_AUX(macor) #macro
#define MACRO_TO_STR(macro) _MACRO_TO_STR_AUX(macor)
// usage:
#define test ABCD
printf("test=%s\n", MACRO_TO_STR(test)); //test=ABCD
1
2
3
4
5
6
7
2
3
4
5
6
7
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54