Concatenating strings using macros

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • girishkeshavan
    New Member
    • Mar 2013
    • 2

    Concatenating strings using macros

    Can someone tell me what is wrong here ?

    Code:
    #define LOG_MACRO(format,args...) printf(format,args)
    
    #define TEST_MACRO(__arg1, __arg2, __format, args...) LOG_MACRO("ARG1: %s, ARG2 : %s" ## __format, ##args)
    
    char* arg1 = "test";
    char* arg2 = "test";
    TEST_MACRO(arg1,arg2,"Testing Macro %s","foo");

    error: pasting ""ARG1: %s, ARG2 : %s"" and ""Testing Macro %s"" does not give a valid preprocessing token
    Last edited by Rabbit; Mar 23 '13, 11:31 PM. Reason: Please use code tags when posting code.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I m not a macro expoert but the args... looks incorrect. Remove the ...

    Ellipsis arguments work in printf because they are coded in the function. There is nothing in your macro support va_arg.

    Comment

    • girishkeshavan
      New Member
      • Mar 2013
      • 2

      #3
      I only need to paste two strings to make it look like one string so that it goes as one argument to one function. args... is not the issue here. Even If remove it I get the same error.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        What compiler are you using?
        Standard support for variable arguments in macros was not available until C99, but it was available as a nonstandard extension in some compilers before that. The first thing to determine is whether your compiler follows the new Standard or if it has its own idiosyncratic way.

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          The error is in this bit

          "ARG1: %s, ARG2 : %s" ## __format

          The first part is a string and __format is also a string, they do not need to be concatenated with ## the compiler automatically concatenates consecutive strings.

          Also you are note using __arg1 and __arg2

          These appear to be strings which probably means you want your macro to be

          Code:
          #define TEST_MACRO(__arg1, __arg2, __format, args...) LOG_MACRO("ARG1: "%s, ARG2 : %s" __format, __arg1, __arg2, ##args)
          If you are using the gcc extension that removes the final , if args is empty.

          Comment

          Working...