What is time_t ultimately a typedef to?

后端 未结 10 2054
陌清茗
陌清茗 2020-11-22 08:34

I searched my Linux box and saw this typedef:

typedef __time_t time_t;

But I could not find the __time_t definition.

相关标签:
10条回答
  • 2020-11-22 09:21

    Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

    0 讨论(0)
  • 2020-11-22 09:23

    What is ultimately a time_t typedef to?

    Robust code does not care what the type is.

    C species time_t to be a real type like double, long long, int64_t, int, etc.

    It even could be unsigned as the return values from many time function indicating error is not -1, but (time_t)(-1) - This implementation choice is uncommon.

    The point is that the "need-to-know" the type is rare. Code should be written to avoid the need.


    Yet a common "need-to-know" occurs when code wants to print the raw time_t. Casting to the widest integer type will accommodate most modern cases.

    time_t now = 0;
    time(&now);
    printf("%jd", (intmax_t) now);
    // or 
    printf("%lld", (long long) now);
    

    Casting to a double or long double will work too, yet could provide inexact decimal output

    printf("%.16e", (double) now);
    
    0 讨论(0)
  • 2020-11-22 09:28

    Standards

    William Brendel quoted Wikipedia, but I prefer it from the horse's mouth.

    C99 N1256 standard draft 7.23.1/3 "Components of time" says:

    The types declared are size_t (described in 7.17) clock_t and time_t which are arithmetic types capable of representing times

    and 6.2.5/18 "Types" says:

    Integer and floating types are collectively called arithmetic types.

    POSIX 7 sys_types.h says:

    [CX] time_t shall be an integer type.

    where [CX] is defined as:

    [CX] Extension to the ISO C standard.

    It is an extension because it makes a stronger guarantee: floating points are out.

    gcc one-liner

    No need to create a file as mentioned by Quassnoi:

    echo | gcc -E -xc -include 'time.h' - | grep time_t
    

    On Ubuntu 15.10 GCC 5.2 the top two lines are:

    typedef long int __time_t;
    typedef __time_t time_t;
    

    Command breakdown with some quotes from man gcc:

    • -E: "Stop after the preprocessing stage; do not run the compiler proper."
    • -xc: Specify C language, since input comes from stdin which has no file extension.
    • -include file: "Process file as if "#include "file"" appeared as the first line of the primary source file."
    • -: input from stdin
    0 讨论(0)
  • 2020-11-22 09:29

    It's a 32-bit signed integer type on most legacy platforms. However, that causes your code to suffer from the year 2038 bug. So modern C libraries should be defining it to be a signed 64-bit int instead, which is safe for a few billion years.

    0 讨论(0)
提交回复
热议问题