I am using C++ in Ubuntu with codeBlocks, boost 1.46 in GCC 4.7 [ yield_k.hpp ]
I get this compile time error:
error : Sleep was not declared in this scope
Code:
#include <iostream>
using namespace std;
int main() {
cout << "nitrate";
cout << flush;
sleep(1000);
cout << "firtilizers";
return 0;
}
How do I resolve this error? I want the program to hang for 1 second.
Sleep is a Windows function. For Unix, look into using nanosleep (POSIX) or usleep (BSD; deprecated). 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).
'Textcolor' was not declared in this scope gives a fault. We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge. Sign Up — It's Free!
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>.
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™.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With