debug.h 1.77 KB
Newer Older
conrad's avatar
conrad committed
1
2
3
4
5
6
7
8
9
10
11
/*
 * A generic debugging printer.
 *
 * Conrad Parker <conrad@metadecks.org>, May 2009
 *
 * Usage:
 *
 * #define DEBUG_LEVEL 3
 * #include "debug.h"
 *
 * ...
conrad's avatar
conrad committed
12
 *     debug_printf (2, "Something went wrong");
conrad's avatar
conrad committed
13
14
15
16
17
18
19
20
21
22
23
 * ...
 *
 * The macro print_debug(level, fmt) prints a formatted debugging message
 * of level 'level' to stderr. You should set the maximum tolerable debug
 * level before including debug.h. If it is 0, or if neither DEBUG_LEVEL
 * nor DEBUG are defined, then the debug_printf() macro is ignored, and
 * none of this file is included.
 */
#ifndef __DEBUG_H__
#define __DEBUG_H__

conrad's avatar
conrad committed
24
25
26
27
28
/* MSVC can't handle C99 */
#if (defined (_MSCVER) || defined (_MSC_VER))
#define debug_printf //
#else

conrad's avatar
conrad committed
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifdef DEBUG
#ifndef DEBUG_LEVEL
#define DEBUG_LEVEL 1
#endif
#endif

#if (DEBUG_LEVEL > 0)

#define DEBUG_MAXLINE 4096

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>

/*
 * debug_print_err (func, line, fmt)
 *
 * Print a formatted error message to stderr.
 */
static void
debug_print_err (const char * func, int line, const char * fmt, ...)
{
  va_list ap;
  int errno_save;
  char buf[DEBUG_MAXLINE];
  int n=0;

  errno_save = errno;

  va_start (ap, fmt);

  if (func) {
    snprintf (buf+n, DEBUG_MAXLINE-n, "%s():%d: ", func, line);
    n = strlen (buf);
  }

  vsnprintf (buf+n, DEBUG_MAXLINE-n, fmt, ap);
  n = strlen (buf);

  fflush (stdout); /* in case stdout and stderr are the same */
  fputs (buf, stderr);
  fputc ('\n', stderr);
  fflush (NULL);

  va_end (ap);
}

/*
 * debug_printf (level, fmt)
 *
 * Print a formatted debugging message of level 'level' to stderr
 */
#define debug_printf(x,y...) {if (x <= DEBUG_LEVEL) debug_print_err (__func__, __LINE__, y);}

#undef MAXLINE

#else
#define debug_printf(x,y...)
#endif

conrad's avatar
conrad committed
90
91
#endif /* non-C99 */

conrad's avatar
conrad committed
92
#endif /* __DEBUG_H__ */