C++错误:未在此范围内声明睡眠
C++ error : Sleep was not declared in this scope
我在 Ubuntu 中使用 C++ 和 codeBlocks,在 GCC 4.7 中提升 1.46 [ yield_k.hpp ]
我收到此编译时错误:
error : Sleep was not declared in this scope
法典:
#include <iostream>
using namespace std;
int main() {
cout << "nitrate";
cout << flush;
sleep(1000);
cout << "firtilizers";
return 0;
}
如何解决此错误? 我希望程序挂起 1 秒钟。
Sleep
是一个Windows函数。
对于Unix,考虑使用nanosleep
(POSIX)或usleep
(BSD;已弃用)。
一个nanosleep
的例子:
void my_sleep(unsigned msec) {
struct timespec req, rem;
int err;
req.tv_sec = msec / 1000;
req.tv_nsec = (msec % 1000) * 1000000;
while ((req.tv_sec != 0) || (req.tv_nsec != 0)) {
if (nanosleep(&req, &rem) == 0)
break;
err = errno;
// Interrupted; continue
if (err == EINTR) {
req.tv_sec = rem.tv_sec;
req.tv_nsec = rem.tv_nsec;
}
// Unhandleable error (EFAULT (bad pointer), EINVAL (bad timeval in tv_nsec), or ENOSYS (function not supported))
break;
}
}
您将需要 <time.h>
和 <errno.h>
,以<ctime>
和<cerrno>
的形式提供C++ 。
usleep
使用起来更简单(只需乘以 1000,因此使其成为内联函数)。但是,无法保证睡眠将在给定的时间内发生,它已被弃用,您需要extern "C" { }
- 包含<unistd.h>
。
第三种选择是使用 select
和 struct timeval
,如 http://source.winehq.org/git/wine.git/blob/HEAD:/dlls/ntdll/sync.c#l1204 所示(这就是葡萄酒模仿Sleep
的方式,它本身只是SleepEx
的包装纸)。
注意:声明为 <unistd.h>
的 sleep
(小写 's')不是可接受的替代品,因为它的粒度是秒,比 Windows 的粒度粗 Sleep
(大写的's'),后者的粒度为毫秒。
关于您的第二个错误,___XXXcall
是特定于 MSVC++ 的令牌(__dllXXX
、__naked
、__inline
等也是如此)。如果你真的需要标准调用,请使用__attribute__((stdcall))
或类似的东西在 gcc 中模拟它。
注意:除非编译目标是 Windows 二进制文件,并且使用的是 Win32 API,否则使用或要求stdcall
是一个不好的迹象™。
如何在 Linux 上的 C++ 程序中使用 usleep:
将其放在名为 s.cpp
的文件中
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
cout << "nitrate";
cout << flush;
usleep(1000000);
cout << "firtilizers";
return 0;
}
编译并运行它:
el@defiant ~/foo4/40_usleep $ g++ -o s s.cpp
el@defiant ~/foo4/40_usleep $ ./s
nitratefirtilizers
它打印了"硝酸盐",等待了1秒钟,然后打印了"firtilizers"
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
const long a=1000000;
long j;
cin >> j;
usleep(a*j);
puts("exit");
}
使用usleep()
睡眠,不要忘记包括unistd.h
(不是cunistd
)
就我而言,它有助于编写 Sleep 而不是 sleep - 很奇怪,但有效!
使用std::this_thread::sleep_for()
#include <chrono>
#include <tread>
int main(int argc , char *argv[])
{
std::this_thread::sleep_for(std::chrono::seconds(2));
}
- 错误:未在此范围内声明'reverse'
- 错误:"imread"未在此范围内声明
- 未在此范围内声明错误 'xy'
- Socklen_t未在此范围内声明
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 'num1'未在此范围内声明
- 如何找到在本地范围内声明的变量的地址?
- NT状态未在此范围内声明
- 变量未在此范围内声明 数组线性搜索
- 包含文件中的 Typdef "未在此范围内声明"
- 'ClassName'和'ClassInstance'未在此范围内声明
- C++ 中的类之间的数据重新循环 - 错误:'<class name>'未在此范围内声明
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 如何修复错误:"vreinterpretq_u32_f64"未在此范围内声明 - 在Android上使用Eigen构建
- 如何修复C++中的"arrStud未在此范围内声明"错误
- 错误:"SHGetKnownFolderPath"未在此范围内声明
- 错误:'Sprite'未在此范围内声明