I have a legacy logging printf-like function in C:
namespace legacy
{
void DoLog(const char* format,...);
}
If is only visible if a corresponding macro is defined (this is legacy too):
#ifdef LOG
# define Log legacy::DoLog
#else
# define Log /* Nothing */
#endif
I have some C++ code, which calls this log like:
Log("Logging started!");
When the LOG macro is not defined, Log("Something"); turns into ("Something"); which is unused code.
I need to suppress these warnings in GCC, and do it only once, of course, so I wrap Log into MyLog as #define MyLog Log and try this:
#define MyLog(...) \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wunused-value\""); \
Log(__VA_ARGS__); \
_Pragma("GCC diagnostic pop");
But these pragmas for some reason do not have any effect
https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html
https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
I would better use inline C++ wrapper with templates for the perfect wrapping, but I cannot cope with it yet...
Any suggestions how to suppress these warnings?
Thank you in advance!
2 Answers 2
Use
#define Log(...)
and then Log("Logging started!"); expands to just ; instead of ("Logging started!");
Comments
I managed to come to the two following solutions:
C++ style inline function, with suppressed warnings and basic Windows and Linux platform definitions used:
template<typename... Args>
inline void MyLog(const char* format, Args... args)
{
#ifndef LOG
# ifdef _MSC_VER // Windows
# pragma warning(push)
# pragma warning(disable: 4548)
# elif defined(__GNUC__) // Linux
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-value"
# endif
#endif
Log(format, (args,...));
#ifndef LOG
# ifdef _MSC_VER // Windows
# pragma warning(pop)
# elif defined(__GNUC__) // Linux
# pragma GCC diagnostic pop
# endif
#endif
}
C style wrapper macro, even without any warnings suppression needed (thanks to @KamilCuk and @user253751):
#ifndef LOG
# define MyLog(...)
#else
# define MyLog(...) Log(__VA_ARGS__)
#endif
Comments
Explore related questions
See similar questions with these tags.
#define Log(...)?how to suppress these warnings?I think it is preferable to have printf warnings even with disabled logging. Then, in case you enable logging, your code is valid and you don't have to deal with a wall of warnings. Consider adding__attribute__((__format__(__printf__, 1, 2)))and doing#define Log(...) 0&&legacy::DoLog(__VA_ARGS__)