Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ using time() with both <time.h> and <ctime> included - which one takes precedence?

I'm using a GNU/Linux distribution with Zsh 5.0.2, Vim 7.3, and GCC 4.8.0 to learn C++.

The following code will not compile due to redefinition of the function foo:

#include <iostream>

int foo()
{
    return 0;
}

int foo()
{
    return 0;
}

int main()
{
    foo();
    return 0;
}

Attempting to compile it:

» g++ -g -pedantic -std=c++11 -Wall -Wextra -Weffc++ foo.cpp -o foo
fail.cpp: In function ‘int foo()’:
fail.cpp:8:5: error: redefinition of ‘int foo()’
 int foo()
     ^
fail.cpp:3:5: error: ‘int foo()’ previously defined here
 int foo()
     ^

However, I noticed that GCC (g++, to be specific) automatically includes <time.h> without me explicitly instructing it to do so. In a program I wrote where std::time() is used but in which I forgot to #include <ctime> and use the std:: prefix this led to time() from <time.h> to be used instead of the corresponding function from <ctime>. I am curious - which time() will be used when both and are included? As far as I can tell, both have a function by that name (and both of them work in a similar or identical fashion), see:

cppreference.com: time.h time()

cppreference.com: ctime time()

Consider the following code:

#include <ctime>
#include <time.h>
#include <iostream>

int function1()
{
    using namespace std;
    cout << "function4: " << time(NULL) << endl;
    return 0;
}

int function2()
{
    using std::time;
    std::cout << "function3: " << time(NULL) << std::endl;
    return 0;
}

int function3()
{
    std::cout << "function2: " << std::time(NULL) << std::endl;
    return 0;
}

int function4()
{
    std::cout << "function1: " << time(NULL) << std::endl;
    return 0;
}

int main()
{
    function1();
    function2();
    function3();
    function4();
    return 0;
}

It may not be perfect but I hope my point gets across. Here, I explicitly included <time.h> for the sake of clarity. The first three do in the ways I'm aware of declare that the std is to be used. The fourth function simply calls time() - which to me seems like either one of the <time.h> and <ctime> variants could be called.

Question 1: Why doesn't this (function4) result in an error or a warning due to ambiguity?

Question 2: Which variant is used and what determines that one takes precedence over the other?

Question 3: Is there a way to, say, output the function name in its entirety during a run or compilation process to see what library is used?

like image 404
totte Avatar asked Dec 12 '22 14:12

totte


1 Answers

If you look inside <ctime>, you will find the following:

#include <time.h>
namespace std
{
   using ::time;
}

This means even if you include <ctime>, it calls the one in <time.h>. Here is a link to the actual header.

like image 199
Jesse Good Avatar answered Dec 14 '22 04:12

Jesse Good