Does using `__DATE__` or `__TIME__` violate the one-definition-rule?

146 views Asked by At

When using __DATE__ or __TIME__ in a header file, the results of the preprocessor for that header inclusion can be somewhat different.

Under which circumstances does using __DATE__ or __TIME__ in a header file violate the one-definition-rule?

As a follow-up: Does the assert header violate the one-definition-rule?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

If __TIME__ gives different results for different translation units, then it must not be used in a context where the same result is required across translation units. This means e.g. initialising an object (e.g. a class member) to __TIME__, where that initialiser is part of a header that gets included in multiple translation units, is going to be problematic.

__DATE__ is less likely to give different results for different translation units if you start a fresh build, but incremental builds, ones that only recompile the files that changed, do make it likely to become a problem as well.

assert is a macro that expands differently depending on how NDEBUG was defined when its header was included, so either the whole project must agree on whether NDEBUG should be defined, or functions defined in headers should avoid using assert.

0
Peter On

The one definition rule is only applicable to variables, functions, class types, enumerations, or templates (e.g. Section 3.2, ISO/IEC 14882, 1998 C++ Standard). __DATE__ or __TIME__ are both predefined macros that expand to a string literal - which is not one of the things that the one-definition rule is applicable to.

assert() is also a preprocessor macro. If its expansion defines a variable, function, class type, enumeration, or template, then its use could potentially violate the one-definition rule, if that definition differed between translation units. Pragmatically, it is difficult to envisage a situation in which an implementation would have an assert() macro that expanded to such a definition.