C++错误:未在此范围内声明睡眠

C++ error : Sleep was not declared in this scope

本文关键字:范围内 声明 错误 C++      更新时间:2023-10-16

我在 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>

第三种选择是使用 selectstruct 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));
}