Find the answer to your Linux question:
Results 1 to 5 of 5
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Running sleep() function on g++


    I am using sleep() function for wait for 1 second.I tried it with gcc and its working properly.But when I used this sleep() function in c++ program and compile with following function then it is giving error as:

    [vineeta@vineeta vineeta]$ g++ thread2.cpp -o thread -lpthread
    thread2.cpp: In function `void* fun_count(void*)':
    thread2.cpp:16: `sleep' undeclared (first use this function)
    thread2.cpp:16: (Each undeclared identifier is reported only once for each
    function it appears in.)

    Why I am grtting this error????

    Please reply

  2. #2
    Linux Engineer Javasnob's Avatar
    Join Date
    Jul 2005
    sleep is defined in stdlib.h. Correct me if I'm wrong, but gcc (and other C compilers) automatically includes certain headers like stdio and stdlib, whereas C++ compilers don't. Try adding #include<cstdlib> to the top of your program and see how that works out.
    Flies of a particular kind, i.e. time-flies, are fond of an arrow.

    Registered Linux User #408794

  3. #3
    I tried but its not working.... where is error.These are my files

    FILE 1 samspec.cpp

    #include <stdio.h>
    #include <cstdlib>

    int main()
    Classcnt cnt;

    FILE 2 samspecCount.cpp

    #include <stdio.h>
    #include <pthread.h>
    void *Counter_fun(void* ptr);

    void Classcnt::createthread(void)
    char *msg1="Count_thread";
    /*Create thread which will execute function*/
    retCntThread=pthread_create(&Count_thread,NULL,Cou nter_fun,(void*)msg1); pthread_join(Count_thread,NULL);


    void* Counter_fun(void* ptr)
    char *message;
    int count,sum;
    int maxcnt=20;
    int i;
    { sleep(1);
    printf("%d %d",sum,count);

    FILE 3 samspecCount.h

    class Classcnt
    pthread_t Count_thread;
    int retCntThread;
    // Classcnt(void);
    // ~Classcnt(void);
    void createthread(void);

    I have compiled it with following options:
    #g++ samspec.cpp samspecCount.cpp -o samspec

    Please help me


  4. $spacer_open
  5. #4
    I have added these two files in specspecCount.cpp also.

    #include "./samspecCount.h"


    Still getting following error:

    g++ samspec.cpp samspecCount.cpp -o samspec
    samspecCount.cpp: In function `void* Counter_fun(void*)':
    samspecCount.cpp:26: `sleep' undeclared (first use this function)
    samspecCount.cpp:26: (Each undeclared identifier is reported only once for each
    function it appears in.)

  6. #5
    got the answer!!!

    u need to add #include<unistd.h>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts