简体   繁体   中英

Clash with identifier 'clock' from time.h

The following program

#include <ctime>

struct clock {};

int main() {
    clock c;
}

fails to compile on both g++ 5.4 and clang 3.8 (Ubuntu 64-bit).

g++ output

clock.cpp: In function ‘int main()’:
clock.cpp:6:11: error: expected ‘;’ before ‘c’
    clock c;
          ^

clang output

clock.cpp:6:5: error: must use 'struct' tag to refer to type 'clock' in this scope
    clock c;
    ^
    struct 
/usr/include/time.h:189:16: note: struct 'clock' is hidden by a non-type declaration of 'clock' here
extern clock_t clock (void) __THROW;
               ^
1 error generated.

The diagnostics vary a little in form, but are related to the same issue. There is a clash with the standard C function clock and the struct of the same name defined in the program. The relevant declaration from time.h :

extern clock_t clock (void) __THROW;

The question is: shouldn't such symbols be in the std namespace, since the program includes <ctime> ? Interestingly, that very declaration sits a couple of lines after a macro which reads __BEGIN_NAMESPACE_STD . In addition, in <ctime> , one can see:

namespace std
{
    using ::clock_t;
    using ::time_t;
    using ::tm;

    using ::clock;
    ...
}

Is there some kind of bug here?

Thank you.

The question is: shouldn't such symbols be in the std namespace...

Yes, and they are. Unfortunately, the C++ standard also allows implementations to put names from C-library derived headers in the global namespace. In this case, you get std::clock and ::clock .

This applies to all the <c*> C++ headers with a corresponding <*.h> version in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM