Home > OS >  Trying to use __VA_ARGS__ in macro C 20
Trying to use __VA_ARGS__ in macro C 20

Time:12-24

I can't wrap my head around this problem. I'm trying to use Variadic arguments in a macro, I got it to work in C 11 with the following code:

#define INFO(format,args...)                                   \
{                                                              \   
    LOG_SEPERATOR;                                             \
    std::cout << "FILE: " << __FILE__ << "\n";                 \
    std::cout << "LINE: " << __LINE__ << "\n";                 \
    std::cout << "FUNCTION: "<< __func__ << "\n";              \
    std::cout << "INFO: \n";                                   \
    ConsoleLog(format,args);                                      \
    LOG_SEPERATOR;                                             \
}                              

                            \

But in C 20 I cannot use:

#define INFO(format,args...) 

The compiler only accepts:

#define INFO(format,...) 

Which means I can do this:

#define INFO(...) static int valuesArray[] = __VA_ARGS__

But I cannot do this:

#define INFO(format,...)
{\
 valuesArray[] = __VA_ARGS__ ; \
LOG_SEPERATOR; \
std::cout << "FILE: " << __FILE__ << "\n"; \
std::cout << "LINE: " << __LINE__ << "\n"; \
std::cout << "FUNCTION: " << __func__ << "\n"; \
std::cout << "INFO: \n"; \
ConsoleLog(format, valuesArray); \
LOG_SEPERATOR; \
}

I get E0969 - the identifier VA_ARGS can only appear in the replacement lists of variadic macros.

I looked for 2 days now, tried different solutions but I believe I'm way over my head here. I was trying to learn something new but now this just became a puzzle that frustrates me.

Thank you in advance.

CodePudding user response:

#define INFO(format,args...) was never standard C . It is an extension supported by some compilers.

Since C 20 there is a standard replacement with __VA_OPT__:

#define INFO(format,...)                                   \
{                                                              \   
    LOG_SEPERATOR;                                             \
    std::cout << "FILE: " << __FILE__ << "\n";                 \
    std::cout << "LINE: " << __LINE__ << "\n";                 \
    std::cout << "FUNCTION: "<< __func__ << "\n";              \
    std::cout << "INFO: \n";                                   \
    ConsoleLog(format __VA_OPT__(,) __VA_ARGS__);                                      \
    LOG_SEPERATOR;                                             \
}      

There also is std::source_location in C 20 which allows implementing this common type of logging macro with a normal function.

  •  Tags:  
  • c
  • Related