Ubuntu 17.10 上的 strptime 错误与 GCC 7.2.0

strptime error on Ubuntu 17.10 with GCC 7.2.0

编译使用 strptime 的程序时:

gcc http_server.c -g -std=c11 -o http_server

我运行进入这个警告:

warning: implicit declaration of function 'strptime'; did you mean 'strftime'? [-Wimplicit-function-declaration]

当我 运行 程序出现分段错误时。经过进一步调试,我发现它在 strptime() 行失败了。我在文件中包含 time.h。如标题所述,我也在使用 gcc 7.2.0。任何帮助将不胜感激,因为我不知所措。

这是我的代码中的一行:

const char TIME_FORMAT[] = "%a, %d %b %Y %H:%M:%S GMT\r\n";
char date[255];
strcpy(date, token + 19);
strptime(date, TIME_FORMAT, request->if_modified_since);

修复了分段错误。与 strftime() 不同,您需要为 tm 结构分配内存。添加了以下内容:

request->if_modified_since = (struct tm*) malloc( sizeof(struct tm) );

但是我在编译时仍然收到讨厌的警告。谁帮我解决了我就给答案。

在编译器命令行上使用-D_XOPEN_SOURCE=700。只是 -D_XOPEN_SOURCE 等同于 -D_XOPEN_SOURCE=1 并且不会得到 strptime() 声明。

您可以使用 500 或 600 而不是 700;你不应该需要。

你也可以使用 -std=gnu11 而不是 -std=c11 然后 strptime() 就会暴露出来,有或没有 -D_XOPEN_SOURCE=700.

您也可以考虑使用 header 来确保使用正确的 POSIX 定义;我就是做这个的。参见 posixver.h,这是 在我的 SOQ 中的 GitHub 上可用(堆栈 溢出问题)存储库作为文件 posixver.hsrc/libsoq sub-directory.