Comma in C/C++ macro passed to another macro

无人久伴 提交于 2020-02-04 04:43:10

问题


I have these macros which generate error in Visual Studio 2015.

#define log_params  __FILE__, __LINE__
#define log(file, line, message, ...) _snprintf_s(nullptr, 0, 0, message,  __VA_ARGS__)

Now calling this never works

 log(log_params, "testing %d", 4)

Any thoughts? I also checked output of preprocessor and it is:

_snprintf_s(nullptr, 0, 0, 4 );

EDIT 1 Intresting finding

#define log(file, line, message, ...) file line

will produce this :

"service.cpp", 164 "testing %d"

Is it normal?


回答1:


The following invocation:

log(log_params, "testing %d", 4)

calls function-like macro log with three actual arguments. Their replacements are not resolved before arguments are "passed" to the macro. In other words, even if log_params contains comma by itself, this comma is not taken into account during function-like macro call resolution.

Thus, you are effectively passing arguments as:

file    ---> __FILE__, __LINE__
line    ---> "testing %d"
message ---> 4

First two parameters are ignored by the replacement, and eventually you obtain:

_snprintf_s(nullptr, 0, 0, 4,  __VA_ARGS__)

which in turns become (as MSVC is happy to ignore requirement for at least one variadic argument):

_snprintf_s(nullptr, 0, 0, 4)



回答2:


This solved my problem

__VA_ARGS__ expansion using MSVC

so now I am using

 #define EXPAND( x ) x
 #define Log_printf( file_name,line, message,...)  _snprintf_s(nullptr, 0,0,message, __VA_ARGS__)
 #define Log(...) EXPAND (Log_printf(__VA_ARGS__))


来源:https://stackoverflow.com/questions/40005189/comma-in-c-c-macro-passed-to-another-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!