in my c++ linux application I have this macro:
#define PRINT(format,arg...) printf(format,##arg)
I want to add a date and time to the beggining of the string that come to PRINT. (it is a log, so I want it at runtime, with variables) how to change this macro in order to d开发者_如何学JAVAo it?
thanks
Do you want compile time or runtime added to the string? If the former:
#define PRINT(format,arg...) printf(__DATE__ ":" __TIME__ " " format,##arg)
will work most of the time.
Note that this will only work if invocations of PRINT only use a string literal for the format string. (ie, PRINT( "foo" ) will work, but PRINT( x ) where x is a variable will not).
If you want a runtime date and time, just append "%s" to the format and then add a call to a function that returns what you want before the arguments.
If you want local runtime date and can use boost.date_time
#define DATE_TODAY to_simple_string(day_clock::local_day())
#define PRINT(format,arg...) printf( (DATE_TODAY + ": " + format).c_str(), ##arg)
You can also use day_clock::universal_day()
if you want UTC time.
Assuming that you want the compile time date and that you compiler has a __DATE__
macro that returns the date
#define PRINT(format,arg...) printf(__DATE__ ": " format,##arg)
If you want runtime date, then you can do something like that:
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)
If you need the current datetime, you have to implement a regular function to do what you ask, since it's impossible for a C macro to return the data you are looking for.
Remember that a C macro is replaced by the C preprocessor at compile time.
精彩评论