localtime_r support on MinGW
Solution 1
Does MinGW support localtime_r ?
No.
If not, does exist a thread-safe alternative? (excluding boost/QT/etc that I can't use)
mingw will use the native localtime function on windows, which is thread safe. (But it's not reentrant, so watch out for that).
Solution 2
My quick solution:
#include <time.h>
#if defined(_MSC_VER)
# define localtime_r(T,Tm) (localtime_s(Tm,T) ? NULL : Tm)
#endif
(Inspired by MinGW code, search for _POSIX_THREAD_SAFE_FUNCTIONS
.)
eang
Updated on July 25, 2022Comments
-
eang almost 2 years
I'm working on a Win32 multithread C++ project and I would like to use one of the
localtime_*
thread-safe alternatives tolocaltime()
.Unfortunately I have to use MinGW compiler, and
localtime_s
cannot be used outside Microsoft stuff.The problem is that neither
localtime_r
is working: the related code snippet is#include <ctime> ... string getCurrentTime() { time_t t; time(&t); struct tm timeinfo; //localtime_s(&timeinfo, &t); localtime_r(&t, &timeinfo); char buf[128]; strftime(buf, 128, "%d-%m-%Y %X", &timeinfo); return string(buf); } ...
This is the compiler output:
error: 'localtime_r' was not declared in this scope
Does MinGW support
localtime_r
?If not, does exist a thread-safe alternative? (excluding boost/QT/etc that I can't use).
EDIT: this is the
<time.h>
provided by my MinGW installation: http://pastebin.com/0CYBfMzg -
Keith4G over 10 yearsOoooh that's nifty. I didn't catch that in the documentation. The POSIX versions use static globals instead.
-
Simon Kissane over 4 yearsActually, MinGW does support
localtime_r
now, provided you#define _POSIX_THREAD_SAFE_FUNCTIONS
before you#include <time.h>
– see definitions here: github.com/mirror/mingw-w64/blob/v6.0.0/mingw-w64-headers/crt/…