【发布时间】:2013-09-04 06:36:34
【问题描述】:
我正在开发一个 Win32 多线程 C++ 项目,我想使用 localtime_* 线程安全替代品之一来替代 localtime()。
不幸的是,我必须使用 MinGW 编译器,而 localtime_s 不能在 Microsoft 之外使用。
问题是localtime_r都没有工作:相关代码sn-p是
#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);
}
...
这是编译器输出:
error: 'localtime_r' was not declared in this scope
MinGW 支持localtime_r 吗?
如果没有,是否存在线程安全的替代方案? (不包括我不能使用的 boost/QT/etc)。
编辑:这是我的 MinGW 安装提供的 <time.h>:http://pastebin.com/0CYBfMzg
【问题讨论】:
-
“
localtime_s不能在 Microsoft 之外使用”是什么意思? MinGW 以 msvcrt.dll 为目标,而 msvcrt.dll 确实定义了localtime_s(其导出为_localtime32_s和_localtime64_s,分别用于 32 位和 64 位time_t)。如果 MinGW 库头文件没有声明它,则自己声明并调用它。有关其声明,请参见 Visual C++ 库头文件。 -
@JamesMcNellis 许多消息来源说只能与微软编译器一起使用。我已经尝试过(包括
<windows.h>)并用g++编译我得到error: 'localtime_s' was not declared in this scope。例如看到:stackoverflow.com/questions/17085603/time-functions-in-mingw/… -
我不知道这些“许多来源”是什么,但它们是错误的。它不是由
<windows.h>声明的,而是由(旧)Visual C++ SDK 中的<time.h>声明的。如果你的MinGW的<time.h>的副本没有声明,你需要自己声明。 -
好的,我已经在问题中发布了我的
<time.h>。确实localtime_s似乎不见了。如何申报?