在Windows8的CodeBlocks中使用cygwin64下的strptime

Using strptime under cygwin64 on Windows 8 in CodeBlocks

本文关键字:cygwin64 下的 strptime Windows8 CodeBlocks      更新时间:2023-10-16

我正试图在我的Windows机器上编译一些最初用linux编写的代码。我已经安装了Cygwin,并为在CodeBlocks中使用进行了设置,它主要起作用。除了给strptime的一个电话,它向我打招呼说:"错误:‘strptime’没有在这个范围内被删除。"我已经在谷歌上搜索了一段时间,但没有结果,有人能解释一下可能出了什么问题吗?我试着把时间包括在内,但是运气不好。

#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#endif
#include <ctime>
#include <cstring>
class Date {
private:
  struct tm _tm;
  string strform;
  static void set_zero(struct tm &_tm) {
    memset(&_tm, '', sizeof(struct tm));
    //    _tm.hour = 0;
  }
  time_t make_time() {
    return mktime(&_tm);
  }
public:
  Date() {
    time_t current = time(NULL);
    _tm = *gmtime(&current);
    char buffer[1024];
    strftime(buffer, 1024, "%b %e %Y", &_tm);
    strform = buffer;
  }
  Date(time_t current) {
    _tm = *gmtime(&current);
    char buffer[1024];
    strftime(buffer, 1024, "%b %e %Y", &_tm);
    strform = buffer;
  }
  Date(string _strform) {
    strform = _strform;
    set_zero(_tm);
    char *result = strptime(strform.c_str(), "%b %e %Y", &_tm);
    assert(result);
    char buffer[1024];
    strftime(buffer, 1024, "%b %e %Y", &_tm);
    strform = buffer;
    //cout << "strform = " << strform << endl;
    //    cout << "length = " << result - strform.c_str() << endl;
    //    cout << "day = " << _tm.tm_mday << endl;
    //    cout << "month = " << _tm.tm_mon << endl;
    //    cout << "year = " << _tm.tm_year << endl;
    //    char buffer[1024];
    //    strftime(buffer, 1024, "%b %e %Y   %H:%M:%S", &_tm);
    //    cout << "buffer = " << buffer << endl;
  }
  Date operator-(int days) {
    return Date(make_time() - days*86400 );
  }
  time_t operator-(Date &other) {
    return (make_time() - other.make_time())/86400.0;
  }
  bool operator<=(Date &other) {
    return make_time() <= other.make_time();
  }
  bool operator<(Date &other) {
    return make_time() < other.make_time();
  }
  bool operator>=(Date &other) {
    return make_time() >= other.make_time();
  }
  time_t to_seconds() {
    return make_time();
  }
  friend ostream &operator<< (ostream &out, const Date &d) {
    return out << d.strform;
  }
  static Date today() {
    return Date();
  }
  string to_string() const {
    return strform;
  }
  const char *to_cstring() const {
    return strform.c_str();
  }
};

请参阅XOPEN_SOURCE上的答案。通过在我的CMakeLists.txt中添加add_definitions(-D_XOPEN_SOURCE=700),我很幸运地编译了strptime。最后,通过打开标头中的功能,编译器可以找到strptime了。

此错误消息表示函数在找到时未声明。看起来strptime()是在Cygwin的time.h文件中声明的(至少在v1.7.25中是这样),所以只需添加:

 #include <time.h>

到您的源文件。注意,strptime()不是标准的C函数。

这只发生在C++11及以上版本中。看起来__STRICT_ANSI__正在被设置,并且strptime()没有在其下定义。解决方法是按如下方式取消对__STRICT_ANSI__的定义。

#ifdef __CYGWIN__
#undef __STRICT_ANSI__
#endif