c++gcccompilationtime.hctime

source is compiled without proper #include


I have a very simple c++ source like this:

#include <iostream>
int main() {
    srand(time(NULL));
}

I am using g++ to compile like this :

g++ ./test.cpp

but it successfully compiles despite the fact that time() function is defined in ctime and it is not included with #include

my professor at university runs the code with visual studio (vc++) but he is unable to run the code without including ctime

Am I missing something here ?

by the way my g++ version is :

g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0


Solution

  • first of all explicitly include what you need,
    (thanks to darkblueflow for pointing it out)
    secondly #include order matters,

    believe or not they can shadow declaration, just switch if first case doesn't work

    #include <cstdlib>
    #include <ctime>
    
    // differs from
    
    #include <ctime>
    #include <cstdlib>
    
    // in some aspects
    

    your best shot is to include headers explicitly and keep this in mind this good luck