GCC版本ntoarm-gcc(GCC)4.4.2
我为所有包装printf()和co的函数添加了'printf'格式属性。它们完全正常,除非使用可变参数宏调用函数。
class Log { [...]
void log_fmt(LogLevel level, const std::string& funcName, const char_t * const logFormatStr, ...) __attribute__ ((format (printf, 4, 5)));
[...] };
不正确的直接电话,如
log.log_fmt(Info, "test", "wrong %u", "type");
产生警告:
format '%u' expects type 'unsigned int', but argument 5 has type 'const char*'
使用宏的相同错误调用不产生警告,但是:
#define LOGI(MSG, ...) log.log_fmt(Info, __func__, (MSG), __VA_ARGS__)
LOGI("wrong %u", "type");
我也可以在这种情况下收到警告吗?我犯了错误还是这种行为?
答案 0 :(得分:1)
此:
#include <iostream>
#include <cstdio>
struct log {
static void logf(std::string, std::string, const char*, ...) __attribute__((format (printf, 3, 4))) {}
};
#define L(m, ...) log::logf("no", __func__, (m), __VA_ARGS__)
int main() {
//log::logf("hi", "hi", "test %u", "hi");
L("test %u", "hi");
}
完美地运作,因为它给出了正确的警告,如下所示:
main.cpp: In function 'int main()':
main.cpp:8:61: warning: format '%u' expects argument of type 'unsigned int', but argument 4 has type 'const char*' [-Wformat=]
#define L(m, ...) log::logf("no", __func__, (m), __VA_ARGS__)
^
main.cpp:12:5: note: in expansion of macro 'L'
L("test %u", "hi");
^
At global scope:
cc1plus: warning: unrecognized command line option "-Wno-undefined-internal" [enabled by default]
所以,我猜这个问题出在位置参数上(你已经4, 5
放在format
属性上,而你似乎应该放3, 4
}。 ..