C++11: "put_time在现代g++中不是std的成员"

13

我在新编译器上遇到一个旧问题。尝试使用std::chrono打印当前时间时,我收到以下错误:

I am having an old problem on a new compiler. While trying to print the current time using std::chrono I receive the following error:

src/main.cpp:51:30: error: ‘put_time’ is not a member of ‘std’
                 std::cout << std::put_time(std::localtime(&time), "%c") << "\n\n";
                              ^~~

有问题的代码片段并没有什么特别之处:

#include <chrono>
...
auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::put_time(std::localtime(&time), "%c") << "\n\n";

这看起来非常像GCC 4.x系列返回的错误,就像各个地方引用的那样:

这种理论唯一的问题是我的GCC是现代的:

$ g++ --version
g++ (GCC) 6.3.1 20161221 (Red Hat 6.3.1-1)
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我还检查了一下我的应用程序是否链接到了适当的库:

$ ldd build/myapp
        ...
        libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007fde97e7b000)
        libc.so.6 => /lib64/libc.so.6 (0x00007fde97595000)

最后,我的编译标志里没有任何奇异的东西:

g++ -g -Wall -Werror -std=c++11 -Wno-sign-compare src/main.cpp -c -o obj/main.o

我能想到的所有检查都表明这应该可以工作。简而言之,怎么回事?


你的代码片段没有包含声明 std::put_time 的头文件。 - eerorika
哎呀,说得好。我在顶部有 #include <chrono>。问题已经更新。此外,它没有抱怨任何其他时间操作,如 std::localtimeto_time_t - MysteryMoose
2
嗯,那似乎就是问题所在了。std::put_time 声明在 <iomanip> 中。 - eerorika
是的,这很尴尬。就是这个问题。我会在4分钟内接受你的答案。希望这能帮助未来的搜索。 - MysteryMoose
1个回答

18

问题在于你包含了错误的头文件。 std::put_time 是在 <iomanip> 中声明的,而不是在 <chrono> 中声明的。


此外,它没有抱怨任何其他时间操作,比如 std::localtimeto_time_t

std::localtime<ctime> 中声明。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接