在我的c ++ linux应用程序中,我有这个宏:
#define PRINT(format,arg...) printf(format,##arg)
我想为进入PRINT的字符串的开头添加日期和时间。 (这是一个日志,所以我想在运行时使用变量) 如何改变这个宏才能做到?
感谢
答案 0 :(得分:1)
您是否希望将编译时间或运行时添加到字符串中?如果是前者:
#define PRINT(format,arg...) printf(__DATE__ ":" __TIME__ " " format,##arg)
大部分时间都会工作。
请注意,这仅在PRINT的调用仅使用字符串文字作为格式字符串时才有效。 (即,PRINT(“foo”)将起作用,但PRINT(x),其中x是变量不会)。
如果你想要一个运行时的日期和时间,只需在格式中附加“%s”,然后添加一个函数调用,该函数在参数之前返回你想要的内容。
答案 1 :(得分:1)
如果您想要本地运行时日期并且可以使用boost.date_time
#define DATE_TODAY to_simple_string(day_clock::local_day())
#define PRINT(format,arg...) printf( (DATE_TODAY + ": " + format).c_str(), ##arg)
如果您想要UTC时间,也可以使用day_clock::universal_day()
。
答案 2 :(得分:0)
假设您需要编译时间日期并且编译器具有返回日期的__DATE__
宏
#define PRINT(format,arg...) printf(__DATE__ ": " format,##arg)
如果你想要运行日期,那么你可以这样做:
std::string format_current_time()
{
// format the time as you like and return it as an std::string
}
#define PRINT(format,arg...) printf("%s: " format, format_current_time.c_str(), ##arg)
答案 3 :(得分:-1)
如果你需要当前的日期时间,你必须实现一个常规函数来完成你的要求,因为C宏不可能返回你想要的数据。
请记住,编译时C预处理器会替换C宏。