home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11436 < prev    next >
Encoding:
Text File  |  1992-07-22  |  1.9 KB  |  62 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!sun-barr!cs.utexas.edu!usc!wupost!darwin.sura.net!jvnc.net!yale.edu!ira.uka.de!math.fu-berlin.de!zrz.tu-berlin.de!cs.tu-berlin.de!jutta
  3. From: jutta@opal.cs.tu-berlin.de (Jutta Degener)
  4. Subject: Re: Variable arguments & macros...
  5. Message-ID: <1992Jul22.155429.14829@cs.tu-berlin.de>
  6. Keywords: macros, varargs
  7. Sender: news@cs.tu-berlin.de
  8. Organization: Techn. University of Berlin, Germany
  9. References: <markkj.711771545@munagin>
  10. Date: Wed, 22 Jul 1992 15:54:29 GMT
  11. Lines: 49
  12.  
  13. markkj@mullian.ee.mu.OZ.AU (Mark Johnston) writes:
  14. >    I'm wondering if anyone has any really devious ways of writing macros
  15. > so that variable arguments can be used.  [..] I have a function
  16. >
  17. > int writeErrorMsg(int quit, char *file, int line, char *format, ...)
  18. [..]
  19. > #define error(x) writeErrorMsg(0, __FILE__, __LINE__, x)
  20. > #define fatal(x) writeErrorMsg(1, __FILE__, __LINE__, x)
  21. [...]
  22. > error("The error code is %1d.", errCode);
  23.  
  24. I did something like that once, although the details are rather messy.
  25. In your error handling module, have three variables and two functions:
  26.  
  27.     #include <stdarg.h>
  28.     #include <stdio.h>
  29.  
  30.     static char * file;
  31.     static int    line, level;
  32.  
  33.     static void writeError(char * fmt, ...) {    /* from C FAQ part 6 */
  34.         va_list ap;
  35.         fprintf(stderr, "file \"%s\", line %d: ", file, line);
  36.         va_start(ap, fmt);
  37.         vfprintf(stderr, fmt, ap );
  38.         va_end(ap);
  39.         fprintf(stderr, "\n");
  40.         if (level == 1) abort();
  41.     }
  42.  
  43.     void (* locateError(int v, int l, char * f))(char *, ...) {
  44.         level = v; file = f; line = l;
  45.         return writeError;
  46.     }
  47.  
  48. Then declare and #define in a header file:
  49.  
  50.     extern void (* locateError(int, int, char *))(char *, ...);
  51.  
  52.     #define error    (locateError(0, __LINE__, __FILE__))
  53.     #define fatal    (locateError(1, __LINE__, __FILE__))
  54.  
  55. And use:
  56.  
  57.     error("switch failed (event.type==%lx)", (long)e.type);
  58.     fatal("%s: failed to allocate %ld bytes.", progname, (long)size);
  59.  
  60. Regards,
  61.     Jutta (jutta@cs.tu-berlin.de)
  62.