may*_*nak 7 c c++ gcc g++ time.h
当我使用该time()函数(即,只是随机化种子rand())但不包括头文件时time.h,它适用于C.例如:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
srand(time(NULL));
for(i=0;i<10;i++){
printf("\t%d",rand()%10);
}
printf("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译上面的代码时,g++无法编译它,因为time.h不包括在内.但gcc可以.
$gcc ra.c
$./a.out
4 5 2 4 8 7 3 8 9 3
$g++ ra.c
ra.c: In function ‘int main()’:
ra.c:8:20: error: ‘time’ was not declared in this scope
srand(time(NULL));
^
Run Code Online (Sandbox Code Playgroud)
它与gcc的版本有关还是只是C/C++之间的区别?
你应该包括<time.h>对时间(2) ,并开启警告.在C中,假定没有可见原型的函数返回int(自C99以来已弃用).所以编译gcc似乎很好,而g++不是.
编译:
gcc -Wall -Wextra -std=c99 -pedantic-errors file.c
Run Code Online (Sandbox Code Playgroud)
你也会看到gcc抱怨它.