When I use the time()
function (i.e., just randomize seed for rand()
) but not include the header file time.h
, it works for C. For example:
#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;
}
When I try to compile the code above, g++
cannot compile it since time.h
isn't included. But gcc
can.
$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));
^
Is it related with version of gcc or just a difference between C/C++ ?
Some reasons are: 1) C++ grammar is more complex than C# or Java and takes more time to parse. 2) (More important) C++ compiler produces machine code and does all optimizations during compilation. C# and Java go just half way and leave these steps to JIT.
I've built gcc many times. It takes a while because the build process is VERY careful to produce a correct SET of compilers for the languages it supports (C, C++, Objective-C, Fortran, Ada, and Go.)
Compilation process in C involves four steps: pre-processing, compiling, assembling, and linking. The preprocessor tool helps in comments removal, macros expansion, file inclusion, and conditional compilation. These commands are executed in the first step of the compilation process.
Only those changed files need to be recompiled. Header files are not compiled directly, Instead, header files are included into other source files via #include .
If the compiler is fed a file of 10 lines, it might take 10 ms to compile, but with 5000 lines, it might take 100 ms. One step that happens before a file is compiled is “preprocessing”. A preprocessor takes all #include "file. h" essentially copy-pastes the contents into each source file, and does this recursively.
You should include <time.h>
for time(2) and turn on the warnings. In C, a function with no visible prototype is assumed to return int
(which has been deprecated since C99). So compiling with gcc
seems fine while g++
doesn't.
Compile with:
gcc -Wall -Wextra -std=c99 -pedantic-errors file.c
and you'll see gcc
also complains about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With