4 ms·
>But of course this is a macro, and means that your logging/assertion code has to be a macro. No, only the code that references __FILE__ needs to be a macro.
by snickerbockers 3y ago
>But of course this is a macro, and means that your logging/assertion code has to be a macro.
No, only the code that references __FILE__ needs to be a macro. Usually what i see is a logging function that takes line and file as arguments, and then a macro that calls the function with __FILE__ and __LINE__.
- deleted 3y ago[deleted]
- ninepoints 3y agoIf you expose a macro that then calls your function, what's the difference between what OP is saying?
- CuriousCosmic 3y agoIf it's a macro, then the preprocessor expands the macro at the callsite (which then expands the __FILE__ and __LINE__ macros in that location). If you use a function, then the __FILE__ and __LINE__ expand inside that function and point to the location inside the function rather than the callsite of the function.
- codr7 3y agoWhich is why you trampoline the function call through a macro to get the expansion, the logging logic can still be inside the function.
- CuriousCosmic 3y agoI agree and that's how I've always handled it. But the OP is trying to solve this purely without macros which is why it is an issue.
- tom_ 3y agoOP seems to be saying that the logging code has to be in a macro. But it doesn't: it can be in a function that's called by a macro. It's the difference between having the logging code in a macro: #define LOG(...)\ do{\ if(g_logging_enabled){\ printf("%s:%d: ",__FILE__,__LINE__);\ printf(__VA_ARGS__);\ }\ }while(0) And having the logging code in a function called by a macro: extern void Log(const char*file,int line,const char*fmt,...); #define LOG(...) (g_logging_enabled?Log(__FILE__,__LINE__,__VA_ARGS__):(void)0)) With the Log function being along these lines: void Log(const char*file,int line,const char*fmt,...){ printf("%s:%d: ",file,line); va_list v; va_start(v,fmt); vprintf(fmt,v); va_end(v); } (This logging code is deliberately simple; in a realistic system, this would be pages of junk dealing with all manner of log categories, log levels, multiple enable flags and their overrides, log target handling, and whatnot. Absolutely the sort of thing that is 0 fun to keep track of in a macro, even before you consider the fact that it's a ton of code to be pasting everywhere you want to log a string.)
- ninepoints 3y agoI understand OP but I haven't seen a single logging implementation that would inline the entire implementation in a macro and I suspect the author of the blog post hasn't either.