C++ error : Sleep was not declared in this scope
In my case it helped to write Sleep and NOT sleep - very strange, but worked!
Sleep
is a Windows function.
For Unix, look into using nanosleep
(POSIX) or usleep
(BSD; deprecated).
A nanosleep
example:
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;
}
}
You will need <time.h>
and <errno.h>
, available in C++ as <ctime>
and <cerrno>
.
usleep
is simpler to use (just multiply by 1000, so make it an inline function). However, it's impossible to guarantee that that sleeping will occur for a given amount of time, it's deprecated, and you need to extern "C" { }
-include <unistd.h>
.
A third choice is to use select
and struct timeval
, as seen in http://source.winehq.org/git/wine.git/blob/HEAD:/dlls/ntdll/sync.c#l1204 (this is how wine emulates Sleep
, which itself is just a wrapper for SleepEx
).
Note: sleep
(lowercase 's'), whose declaration is in <unistd.h>
, is not an acceptable substitute, since its granularity is seconds, coarser than that of Windows' Sleep
(uppercase 's'), which has a granularity of milliseconds.
Regarding your second error, ___XXXcall
is a MSVC++-specific token (as are __dllXXX
, __naked
, __inline
, etc.). If you really need stdcall, use __attribute__((stdcall))
or similar to emulate it in gcc.
Note: unless your compile target is a Windows binary and you're using Win32 APIs, use of or a requirement for stdcall
is A Bad Sign™.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
const long a=1000000;
long j;
cin >> j;
usleep(a*j);
puts("exit");
}
use usleep()
Insted of sleep and Don't forget to Include unistd.h
(Not cunistd
)
How to use usleep in a C++ program on linux:
Put this in a file called s.cpp
#include <iostream>
#include <unistd.h>
using namespace std;
int main() {
cout << "nitrate";
cout << flush;
usleep(1000000);
cout << "firtilizers";
return 0;
}
Compile it and run it:
el@defiant ~/foo4/40_usleep $ g++ -o s s.cpp
el@defiant ~/foo4/40_usleep $ ./s
nitratefirtilizers
It printed 'nitrate', waited 1 second, then printed 'firtilizers'