Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can C compile time() without its library?

Tags:

c++

c

gcc

g++

time.h

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++ ?

like image 736
maynak Avatar asked May 16 '15 13:05

maynak


People also ask

Why does building C++ take so long?

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.

Why does GCC take so long to compile?

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.)

How does compilation work in C?

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.

Do header files need to be compiled?

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 .

How long does it take to compile C++?

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.


1 Answers

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.

like image 182
P.P Avatar answered Oct 16 '22 20:10

P.P