[try Beta version]
Not logged in

 
Undefined reference to "sleep(unsigned int)"

Jan 25, 2012 at 11:28pm
I have a program written with Windows-only code that I'm converting to multi platform. I've taken the windows only function,

 
Sleep(unsigned int milliseconds);


and am replacing it with

 
sleep(unsigned int seconds);


I'm getting an error "undefined reference to "sleep(unsigned int)".
The article that describes my sleep function states that it needs "unistd.h" within the program for it to work. I have that included within the source code, so I am confused as to why it is not defined. Would you help me?

Here is the article.

http://www.manpagez.com/man/3/Sleep/

Here is where I have <unistd.h> included. My entire project is within one source file.

1
2
3
4
5
6
7
#include <iostream> 
#include <string> // for use of strings
#include <limits> // for use of "cin.ignore();"
#include <unistd.h>

     unsigned int
     sleep(unsigned int seconds);


Here is an example of how I am using the sleep function.

1
2
3
4
5
                sleep(1); 
		cout <<"1";             
		sleep(1 / 3);
		cout << ".";
		sleep(1 / 3);


I am compiling and linking using DevC++. The code compiles, the linker gives me the error.
Jan 26, 2012 at 7:40am
Please remove your prototype. You should pick that up from unistd.h.
Jan 30, 2012 at 11:03pm
Removed it, getting the error that sleep is now undeclared. What's the problem? I've heard that DevC++ contains the required libraries and headers for unistd.h to be included properly. I haven't edited the compiler at all.
Jan 30, 2012 at 11:16pm
I don't have unistd.h within DevC++. Comes back to the same error, how do I find Unistd.h?
Jan 30, 2012 at 11:17pm
Erm, the function isn't available under Windows.
Jan 30, 2012 at 11:19pm
I'm trying to find a function that's multi platform, so I can't use Sleep (which is windows specific). How am I supposed to make this program multi platform if I can't compile it on Windows?
Jan 30, 2012 at 11:21pm
You just make a wrapper function that calls the correct function depending on the platform.
Or you use an existing multi-platform library that does just that.
Jan 30, 2012 at 11:24pm
How would I call such a function? I'm imagining that requiring me to have the required headers (unistd.h), which I can't with Windows.
Jan 30, 2012 at 11:35pm
That's why you include <windows.h> and not <unistd.h> on Windows.

sleep.hpp:
void msleep(int milliseconds);

sleep.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifdef __WIN32__
#include <windows.h> 
#else
#include <unistd.h>
#endif
void msleep(int milliseconds)
{
  #ifdef __WIN32__
  Sleep(milliseconds);
  #else
  usleep(static_cast<useconds_t>(milliseconds)*1000); //or use nanosleep on platforms where it's needed
  #endif
}


That's the basic idea.
You only would call your own function msleep in your programs.
Topic archived. No new replies allowed.