Debugging tool


I am working on a project where the only debugging tool I have is the use of printf's embedded within my program. To turn this off for release I have written a function which calls the printf function and I am using a #define/#undef.

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
#define  DEBUG
// #undef   DEBUG

char  St[256];

...
...

   dbprintf( "\n%s %d Got this far.", __FILE__, __LINE__ );

...
...

static int dbprintf( char *fmt, ... )
{
   va_list        list;

   if( DEBUG )
   {
      va_start( list, fmt );
      vsprintf( St, fmt, list );
      va_end( list );
      printf( "%s", St );
   }
   return 0;
}


This works, but it would be easier if I could somehow embedded __FILE__ and __LINE__ in the dbprintf function. However if I replace:

 
      printf( "%s", St );


in the dbprintf function with:

 
      printf( "%s %d %s", __FILE__, __LINE__, St );


I get the filename and line number of the printf statement in the dbprint function, when I want the filename and line number of the statement calling the dbprintf function.

I would like for the dbprintf function to support multiple parameters just as printf does (i.e.):

 
   dbprintf( "\nGot this far, A = %d.", A);



Any suggestions?

Note: The project is actually in C not C++. So any C++ solutions will not be much help.
Last edited on
That's not possible. __LINE__ and __FILE__ aren't real variables. When you compile your program they are just replaced by the line and file they are in. You have to pass them as arguments.
I was thinking that there maybe a way to replace the function with a macro, but I don't know how (if it is even possible) to create a macro that would accept an unspecified number of arguements.
C99 introduced variadic macros:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

#define foo( fmt, ... ) printf( "file %s line %d: " fmt, __FILE__, __LINE__, __VA_ARGS__ )

int main()
  {
  foo( "c = %c, s = %s\n", 'A', "Hello world!" );
  foo( "%s\n", "Bye now!" );
  return 0;
  }


D:\prog\foo> gcc -Wall -std=c99 -pedantic a.c

D:\prog\foo> a
file vm.c line 8: c = A, s = Hello world!
file vm.c line 9: Bye now!

D:\prog\foo>


The GCC had them long before. See http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html

Hope this helps.
Last edited on
Topic archived. No new replies allowed.