Search code examples
c++compilationcygwin

gettimeofday() not declared in this scope - Cygwin


Can cygwin make use of gettimeofday()? I'm getting the error:

lab8.cpp: In function ‘int main()’:
lab8.cpp:62:30: error: ‘gettimeofday’ was not declared in this scope
     gettimeofday(&start, NULL);
                              ^
makefile:14: recipe for target 'lab8.o' failed
make: *** [lab8.o] Error 1

I definitely included <sys/time.h>. Is there a package that I have to install or does it just not work on Windows?

EDIT: Here's a simple test that yields the same error:

#include <sys/time.h>

int main() {
    struct timeval start;

    gettimeofday(&start, NULL);
}

With the error:

$ g++ -c -Wall -g -std=c++11 test.cpp -o test.o
test.cpp: In function ‘int main()’:
test.cpp:6:30: error: ‘gettimeofday’ was not declared in this scope
     gettimeofday(&start, NULL);

Solution

  • You need to define _BSD_SOURCE to include the declaration gettimeofday (since glibc2.2.2 according to link below)

    #define _BSD_SOURCE
    
    #include <sys/time.h>
    
    int main() {
        struct timeval start;
    
        gettimeofday(&start, NULL);
    }
    

    gettimeofday() - Unix, Linux System Call