I am learning C.
In this program
I use sleep function to slowdown a count down.
My text book doesn't specify a library I should include to use the sleep function.
So I use it without including any special library for it and it works.
But it gives me this warning message in codeblocks.
I tried to include <windows.h> but still the same warning message appears.
warning D:\Project\C language\trial8\trial8.c|19|warning: implicit
declaration of function `sleep'|
And here is my code.
#include <stdio.h>
int main()
{
int start;
do
{
printf("Please enter the number to start\n");
printf("the countdown (1 to 100):");
scanf("%d",&start);
}
while(start<1 || start>100);
do
{
printf("T-minus %d\n",start);
start--;
sleep(3000);
}
while(start>0);
printf("Zero!\n Go!\n");
return(0);
}
I want to know what does the warning message mean? How important is it? Is there anything that I should do about it? Note that the program works anyway.
The issue is in the libraries (header files):
on Windows:
#include <windows.h> and Sleep(1000); => 1000 milliseconds
on Linux:
#include <unistd.h> and sleep(1); => 1 second
The function sleep is not part of C programming language. So, C compiler needs a declaration/prototype of it so that it can get to know about about number of arguments and their data types and return data type of the function. When it doesn't find it, it creates an Implicit Declaration of that function.
In Linux, sleep has a prototype in <unistd.h> and in windows, there is another function Sleep which has a prototype in <windows.h> or <synchapi.h>.
You can always get away with including header, if you explicitly supply the prototype of the function before using it. It is useful when you need only few functions from a header file.
The prototype of Sleep function in C on windows is:
VOID WINAPI Sleep(_In_ DWORD dwMilliseconds);
Remember, it is always a good practice to supply the prototype of the function being used either by including the appropriate header file or by explicitly writing it. Even, if you don't supply it, compiler will just throw a warning most of the time and it will make an assumption which in most cases will be something that you don't want. It is better to include the header file as API might change in future versions of the Library.
Windows doesn't have the sleep function. Instead, it has Sleep, which takes the number of milliseconds to sleep:
VOID WINAPI Sleep(
_In_ DWORD dwMilliseconds
);
You'll need to either #include <windows.h> or #include <synchapi.h>, depending on the version of Windows you're running. See MSDN for more details.
Update in 2022:
As it is stated on the Linux man page here we need to include unistd.h and should do fine for all OS.
#include <stdio.h>
#include <unistd.h>
int main()
{
sleep(1); /* sleep for 1 second*/
printf("END\n");
return 0;
}
To make it more cross-platform, try this:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
Related
I am trying something in C on hp-nonstop(tandem),
As part my task is to wait for sometime.
I try to use the
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("Something");
sleep(5);
printf("Something");
fflush(stdout);
}
}
It's compiling without any problem,
While running it is giving ABENDED: each time different no.
The result calling sleep() from guardian environment is undefined. That might be leading to ABEND that you mentioned. If you want to wait for some time in guardian hp-nonstop environment, you should call DELAY(). It takes centi-seconds as arguments. So if you want to add delay of 5 seconds, you should call it as DELAY (500). You also need to include the header #include<cextdecs(DELAY)>
I'm tasked with creating a popen() function using Pipes, which I have already completed. The catch is that the function must ALSO be named popen, not mypopen or popen2 etc.
I'm looking for someone to guide me in the right direction as to how I can accomplish this.
Currently I have a header file popen.h and another filed popen.c that I have created.
popen.h just has
void popen(char *arr[]);
While popen.c has the actual popen function code (Which works, just not when the function name is popen).
Currently I'm getting a previous declaration error upon compilation when my function is called popen.
How can I let the compiler choose between the two different popen functions, mine and stdio.h version.
Just #define popen my_popen before declaring, defining and using your function, but after including <stdio.h>.
popen.h
#define popen my_popen
void popen(char *arr[]);
popen.c
#include <stdio.h>
#include "popen.h"
void popen(char *arr[]){ printf("that's NOT the stdio's popen\n"); }
main.c
#include <stdio.h>
#include "popen.h"
int main(void){
popen(0); printf("done\n");
}
Similarly, you can hide the stdio's popen by defining popen to stdio_popen before including <stdio.h> and undefining it afterwards, if you really want to have a symbol named popen:
#define popen stdio_popen
#include <stdio.h>
#undef popen
void popen(char *arr[]){ printf("that's NOT the stdio's popen\n"); }
int main(void){
popen(0); printf("done\n");
}
$ nm a.out | grep popen
0000000000001160 T popen
Such nasty tricks are only useful when having to combine ornery source codes which pollute each other's namespace. There's zero reason to name a function you just wrote popen() and not something else, unless it's a drop-in replacement, with the same interface as the standard one.
If you want to have popen safely you must also make sure that you aren’t using <stdio.h>as this is where the normal popen is located, and your linker will not like it if there are two identical symbols named popen.
Whenever I try to use srand function I get this warning
"implicit declaration of function 'time' [-Wimplicit-function-declaration]|"
and a windows error report appears when running the compiled file,
I'm a novice to c programming, I found this on a text book, but it doesn't work for me.
srand (time());
int x= (rand()%10) +1;
int y= (rand()%10) +1;
printf("\nx=%d,y=%d", x,y);
What do I need to correct this?
You need to make sure that you #include the right headers, in this case:
#include <stdlib.h> // rand(), srand()
#include <time.h> // time()
When in doubt, check the man pages:
$ man rand
$ man time
One further problem: time() requires an argument, which can be NULL, so your call to srand() should be:
srand(time(NULL));
Note that time() function uses current time (expressed in seconds since 1970) both in its return value and in its address argument.
I had this issue, and the problem was that in windows you need to include sys/time.h, but in linux you need time.h and I didn't notice.
I fixed this by adding a simple platform check:
#ifdef _WIN32
#include <sys/time.h>
#else
#include <time.h>
#endif
Note that this is for windows and linux, because that's what I needed for my program.
I am using the Big Nerd Ranch book Objective-C Programming, and it starts out by having us write in C in the first few chapters. In one of my programs it has me create, I use the sleep function. In the book it told me to put #include <stdlib.h> under the #include <stdio.h> part. This is supposed to get rid of the warning that says "Implicit declaration of function 'sleep' is invalid in C99". But for some reason after I put #include <stdlib.h>, the warning does not go away.. This problem does not stop the program from running fine, but I was just curious on which #include I needed to use!
The sleep man page says it is declared in <unistd.h>.
Synopsis:
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
sleep is a non-standard function.
On UNIX, you shall include <unistd.h>.
On MS-Windows, Sleep is rather from <windows.h>.
In every case, check the documentation.
this is what I use for a cross-platform code:
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main()
{
pollingDelay = 100
//do stuff
//sleep:
#ifdef _WIN32
Sleep(pollingDelay);
#else
usleep(pollingDelay*1000); /* sleep for 100 milliSeconds */
#endif
//do stuff again
return 0;
}
What is the proper #include for the function 'sleep()'?
sleep() isn't Standard C, but POSIX so it should be:
#include <unistd.h>
sleep(3) is in unistd.h, not stdlib.h. Type man 3 sleep on your command line to confirm for your machine, but I presume you're on a Mac since you're learning Objective-C, and on a Mac, you need unistd.h.
Given that sleep is a non-standard function, I created a sleep function with the standard library time.h
#include <time.h>
void sleep(double s) {
time_t cur_time = time(NULL);
while ((difftime(time(NULL), cur_time)) < s);
}
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
This was asked during an interview.
I was told to print something on console.
anybody?
Really surprised that nobody posted this yet:
#include <stdio.h>
#if 0
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#endif
int main()
{
printf("Hello, World!");
return 0;
}
Prints at runtime and no undefined behavior whatsoever.
weird question...
int main(void)
{
printf("hello");
return 0;
}
#define main int lol
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#include <stdio.h>
#define exit(c) return puts("foobar"),0
over main
One implementation defined way would be to use the pragma directives to print during compilation.
#pragma message "Compiling " __FILE__ "..."
Or, you could do this with some macros and a printf (but not without introducing UB in some aspect or the other) at runtime.
#define exit(x) printf("Hello, world!")
int main() {
exit(0);
return 0; /* if pre-C99 */
}
#include <stdio.h>
#pragma message("Some foobar")
#error This is an error message
int main()
{
exit(0);
}
I think the interviewer wanted to know if you're aware of the #error directive ... just my 2 cents.
Most answers involve the #define c-preprocessor instruction to change what the program means. Most compilers also support something like
#pragma startup foo()
details depend on the compiler vendor. You can make code run BEFORE main(*) is called that way.
#define exit(x) (printf("Bye"))
int main(int argc,char* argv)
{
exit(0);
getchar();
return 0;
}
Solution 1.
This works without any preprocessor directives in cl and gcc, although I've not tested to make sure I'm not using any extensions:
#include <stdio.h>
static void exit() {
printf("Hello world");
}
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
I think it's valid but I can't remember if masking a standard library function is allowed or not.
Solution 2
As several other answers have specified, you can use preprocessor directives, eg:
#define main or exit to be something that calls ifdef
use #if 0 to prevent the existing code being compiled
using #pragma message or #error to print a message at compile time
using #pragma startup to use a different function as main or to run start-up code before main.
Solution 3
If your compiler supports any C++ features in addition to C, there are many answers:
Declare a class with a constructor and a static variable of that type
Put the existing "main" function into a separate namespace (or class definition) and write a different global main
Solution 4
I also looked for any way of forcing a run-time error (stack overflow, out of memory, null dereference, tc), which would normally cause the program to print something, but couldn't find any way that didn't involve running extra code, in which case the extra code might as well be printf.
If you interpreted the question to mean you could not or were not allowed to edit the file by commenting out /* */ or using #ifdef _COMMENT_ME_OUT__ #endif respectively above and below the section you are not allowed to edit and then introducing a new main, then you should give an answer of using another .c file.
If you cannot find a workaround to edit that file, then use a different c file.