On Windows I can call:
_time32(__time32_t); // to get 32-bit time_t
_time64(__time64_t); // to get 64-bit time_t
(both in 32 and 64-bit programs)
Is there any way do this in Linux (compiling with GCC)?
On Windows I can call:
_time32(__time32_t); // to get 32-bit time_t
_time64(__time64_t); // to get 64-bit time_t
(both in 32 and 64-bit programs)
Is there any way do this in Linux (compiling with GCC)?
Apparently, no it's not possible. For starters, there is only one
time()
function in Linux, notime32()
ortime64()
.After searching for a while, I can see that it's not libc's fault, but the culprit is actually the kernel.
In order for libc to fetch the current time, it need to execute a system call for it: (Source)
The system call is defined as: (Source)
The function
get_seconds()
returns anunsigned long
, like so: (Source)And
timekeeper.xtime_sec
is actually 64-bit: (Source)Now, if you know your C, you know that the size of
unsigned long
is actually implementation-dependant. On my 64-bit machine here, it's 64-bit; but on my 32-bit machine here, it's 32-bit. It possibly could be 64-bit on some 32-bit implementation, but there's no guarantee.On the other hand,
u64
is always 64-bit, so at the very base, the kernel keeps track of the time in a 64-bit type. Why it then proceeds to return this as anunsigned long
, which is not guaranteed to be 64-bit long, is beyond me.In the end, even if libc's would force
time_t
to hold a 64-bit value, it wouldn't change a thing.You could tie your application deeply into the kernel, but I don't think it's even worth it.
No
time64()/time32()
function are included into standard libraries.No
time32_t/time64_t
defines are contemplated in standard headers.time_t
is defined intotime.h
astypedef __time_t time_t
;Following a long chain of redefines, you'll discover that
__time_t
is defined as 32 bit on 32 bit machines and 64bit on 64 bit machines.Many answers above said that this is impossible, but that's entirely incorrect. It was not possible at that time yet people had been talking about fixing it for years. Finally 64-bit time support on 32-bit platforms was introduced to the Linux 5.1 kernel with the addition of the new
*time64
syscalls. Look at this table you can see that those syscalls aren't available on any 64-bit platforms. Now if you're writing code for 32-bit systems you can callclock_gettime64
directly (from inline assembly or C withsyscall()
) to get the current timeHowever after that you're completely on your own. If you want full userspace support you must be on Linux 5.6 or higher along with musl 1.2+ or glibc 2.32+. Just rebuild your code and your
time_t
will become 64-bit longFor more information
If you really need this, why not roll your own?
And similarly for
get_mytime64()
.If you do not care about overflow, a simple
return time(NULL);
would work for both functions thanks to C's implicit numeric conversions.Use this library: https://github.com/evalEmpire/y2038