I would like your help with a project coded in C++. I would like to keep the project…
- User
I would like your help with a project coded in C++. I would like to keep the project compiling with C++11, so do not suggest using features from higher versions of C++.
In this function:
template <typename... Args> void IMF_LOG(std::string format, Args const&... args) { SDL_LockMutex(m_loggerMutex); printf((format + "\n").c_str(), args...); SDL_UnlockMutex(m_loggerMutex); }
the line: printf((format + "\n").c_str(), args...);
raises the error: error: format not a string literal and no format arguments [-Werror=format-security]
in a compiler.
Here is an example of a call to IMF_LOG in the code:
log_error("executeMidiCommand_NoteONOFF_internal(midichannel=%i, note=%s, velocity=0x%02X)", getMidiChannel(instr), noteNumber.toString().c_str(), velocity);
where the function "log_error" is as follows: template <typename... Args> void log_error(std::string format, Args const&... args) { IMF_LOG("[%s] [ERROR] " + format, getCurrentThreadName().c_str(), args...); }
The parameter "velocity" is of type "KeyVelocity", a user-defined struct: struct KeyVelocity { uint8_t value;
KeyVelocity() : value(0) {} explicit KeyVelocity(uint8_t v) : value(v) {}}; static_assert(sizeof(KeyVelocity) == 1, "KeyVelocity needs to be 1 in size!");
How do you suggest resolving the compiler error?
- Assistant
To resolve the compiler error, you can use a combination of
std::ostringstreamto build the formatted string and then print it usingprintfor other logging methods. Here's the modifiedIMF_LOGfunction that does this:#include <sstream> #include <cstdio> #include <string> #include <SDL2/SDL.h> template<typename T> void append_format(std::ostringstream& stream, T arg) { stream << arg; } template<typename T, typename... Args> void append_format(std::ostringstream& stream, T arg, Args... args) { stream << arg; append_format(stream, args...); } template <typename... Args> void IMF_LOG(std::string format, Args const&... args) { std::ostringstream stream; append_format(stream, format.c_str(), "\n", args...); std::string result = stream.str(); SDL_LockMutex(m_loggerMutex); printf("%s", result.c_str()); SDL_UnlockMutex(m_loggerMutex); }The
append_formatfunction is added to handle appending the format string and arguments to the . This function is called in the function, where it appends the appropriate strings and arguments to the stream. After that, we use to print the resulting formatted string.