C++ __TIME__ is different when called from different files

最后都变了- 提交于 2019-12-04 05:47:48

问题


I encountered this strange thing while playing around with predefined macros. So basically, when calling __TIME__ from different files, this happens:

Is there anyway I can fix this? Or why does this happen?
All I am doing is printf("%s\n", __Time__); from different functions in different sources.


回答1:


Or why does this happen?

From the docs:

This macro expands to a string constant that describes the time at which the preprocessor is being run.

If source files are compiled at different times, then the time will be different.

Is there anyway I can fix this?

You could use a command line tool to generate the time string, and pass the string as a macro definition to the compiler. That way the time will be the same for all files compiled by that command.




回答2:


To answer your original question: __TIME__ is going to be different for different files because it specifies the time when that specific file was compiled.

However, you're asking X-Y problem. To address what you're actually trying to do:

If you need a compilation-time value, you're better off letting your build system specify it. That is, with make or whatever you're using, generate a random seed somehow, then pass that to the compiler as a command-line option to define your own preprocessor macro (e.g. gcc -DMY_SEED=$(random_value) ...). Then you could apply that to all C files that you compile and have each of them use MY_SEED however you want.




回答3:


Well, I think your use case is kind of weird, but a simple way to get the same time in all files is to use __TIME__ in exactly one source file, and use it to initialize a global variable:

compilation_time.h:

const char *compilation_time;

compilation_time.c:

#include "compilation_time.h"
const char *compilation_time = __TIME__;

more_code.c:

#include "compilation_time.h"
...
    printf("%s\n", compilation_time);

If you really want to construct an integer as in your comment (which may be non-portable as it assumes ASCII), you could do

seed.h:

const int seed;

seed.c:

#include "seed.h"
const int seed = (__TIME__[0] - '0') + ...;

more_code.c:

#include "compilation_time.h"
...
    srand(seed);


来源:https://stackoverflow.com/questions/54620907/c-time-is-different-when-called-from-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!