implicit declaration of function usleep

前端 未结 6 1863
庸人自扰
庸人自扰 2020-12-14 07:21
gcc (GCC) 4.6.3
c89

I am trying to use usleep. However, I keep getting the following warning:

implicit declarat

6条回答
  •  有刺的猬
    2020-12-14 07:34

    Add the following to the top of your code:

    // For `nanosleep()`:
    #include 
    
    #define __USE_POSIX199309
    #define _POSIX_C_SOURCE 199309L
    

    And then use nanosleep() instead, to create your own sleep_us() function to sleep a set number of microseconds:

    void sleep_us(unsigned long microseconds)
    {
        struct timespec ts;
        ts.tv_sec = microseconds / 1e6;             // whole seconds
        ts.tv_nsec = (microseconds % 1e6) * 1e3;    // remainder, in nanoseconds
        nanosleep(&ts, NULL);
    }
    

    For compiling and running on Linux Ubuntu, I created a sleep_test.c file and used:

    gcc -Wall -g3 -std=c11 -o sleep_test sleep_test.c && ./sleep_test
    

    References:

    1. (This is intentionally a circular reference: see my comments under this answer): Is there an alternative sleep function in C to milliseconds?
    2. http://man7.org/linux/man-pages/man2/nanosleep.2.html

提交回复
热议问题