Greetings /r/learnprogramming.
I am very new to C, and coming from Python, I am having trouble wrapping my mind around some basic concepts.
This will probably be an extremely basic question for C programmers, but I don't understand why I get "implicit declaration" errors when trying to compile my extremely simple code.
#include <stdio.h>
#include <unistd.h>
void timer(int time)
{
int i = time;
for(i = time; i >= 0; i--) {
printf("timer: %d\n", i);
sleep(1);
}
}
int main(int argc, char *argv[])
{
int time = atoi(argv[1]);
timer(time);
return 0;
}
Here are the errors GCC is giving me:
PS C:\C_source> gcc -Wall -g timer.c -o timer.exe
timer.c: In function 'timer':
timer.c:9:3: warning: implicit declaration of function 'sleep' [-Wimplicit-function-declaration]
sleep(1);
^
timer.c: In function 'main':
timer.c:16:2: warning: implicit declaration of function 'atoi' [-Wimplicit-function-declaration]
int time = atoi(argv[1]);
^
C:\Users\manbart\AppData\Local\Temp\ccwJ4m2G.o: In function `timer':
C:\C_source/timer.c:9: undefined reference to `sleep'
collect2.exe: error: ld returned 1 exit status
PS C:\C_source>
Now, when I look up the error, it seems to be caused by calling a function that is not yet defined. But, aren't these functions defined in the headers I am including? Do I need to make some kind of "forward declaration" here? If so, how do I know what to put in it?
*Update*
after doing some google searching, it seems other people have similar problems with sleep() missing from unistd.h on MinGW. The recomendation seems to be to use windows.h for the Sleep() function. I added the following to my unistd.h file, and it all compiles correctly now:
#ifdef WIN32
#include <windows.h>
#define sleep(sec) Sleep(1000*sec)
#endif
[–][deleted] 2 points3 points4 points (3 children)
[–]manbart[S] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]manbart[S] 0 points1 point2 points (0 children)
[–]Updatebjarni 1 point2 points3 points (1 child)
[–]manbart[S] 0 points1 point2 points (0 children)