gettimeofday()未在此范围内声明 - Cygwin

Joh*_*ohn 1 c++ cygwin compilation

cygwin可以使用gettimeofday()吗?我收到错误:

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
Run Code Online (Sandbox Code Playgroud)

我肯定包括在内<sys/time.h>.是否有我必须安装的软件包,或者它是否在Windows上无法运行?

编辑:这是一个产生相同错误的简单测试:

#include <sys/time.h>

int main() {
    struct timeval start;

    gettimeofday(&start, NULL);
}
Run Code Online (Sandbox Code Playgroud)

有错误:

$ 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);
Run Code Online (Sandbox Code Playgroud)

小智 7

您需要定义_BSD_SOURCE以包含声明gettimeofday(因为glibc2.2.2根据下面的链接)

#define _BSD_SOURCE

#include <sys/time.h>

int main() {
    struct timeval start;

    gettimeofday(&start, NULL);
}
Run Code Online (Sandbox Code Playgroud)

gettimeofday() - Unix,Linux系统调用