CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 1999
    Posts
    2

    C++ Macros w/Variable Arguments

    I would like to create a macro (#define xxx(x,x) etc.) that will accept a varable number of arguments. I then want to send the variable number of arguments to a printf/FormatMessage style code. Can I do this in a macro? It's use would be:

    #define SENDLOG(x,...) SendLog(x, __LINE__, __FILE__, ...)

    Doesn't work. Anyone have any tricks?

    Shawn Wildermuth
    NetSuite Development Corporation

  2. #2
    Join Date
    May 1999
    Posts
    8

    Re: C++ Macros w/Variable Arguments

    I would write a function for it


  3. #3
    Join Date
    May 1999
    Posts
    123

    Re: C++ Macros w/Variable Arguments

    There are a couple ways of handling this. First of all, you can write a function instead of a macro. Since this sort of thing is often done for debugging, you usually use a pair of functions, one of which is a nop, and choose between them based on whether something is defined or not.

    Although it's a little ugly, you can also get a macro to treat a number of things as a single argument by enclosing them in parentheses. For example, the following has been tested and runs:

    #include <stdio.h>

    #define SENDLOG(fmt, args) \
    fprintf(stderr, "%d %s: " fmt, __LINE__, __FILE__, args)

    // ...

    int main() {

    extern int errno;

    char errname[20] ="A mock error string";

    SENDLOG("%d %s", (errno, errname));
    return 0;
    }


    The universe is a figment of its own imagination.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured