简体   繁体   中英

timespec not found in time.h

I am having to rewrite an application from C++ to C. I am using gcc and Eclipse on Ubuntu 12.04. In doing so I have come across this error

../src/TTNoddy.c: In function ‘main’:
../src/TTNoddy.c:16:2: error: unknown type name ‘timespec’

Here is my code snippet that reproduces the problem

#include <time.h>

int main(void) {

    timespec TS;
    TS.tv_nsec = 1;

    return 0;
}

I am confused here - I am a C++ coder and never written a pure C application in my life, but the man page for clock_gettime clearly indicates that timespec is found in the time.h header file which I am including here. What have I missed?

timespec is a struct , you need to explicitly tell the compiler this. If you carefully read the man page you can see it is stated so.

This should work:

#include <time.h>

int main(void) {
    struct timespec TS;
    TS.tv_nsec = 1;

    return 0;
}

Additional note : If it had been defined as a typedef struct , you would not have needed to add the struct part manually. But, you should assume that most/all pure C structs are not defined as a typedef

It should not be just timespec as timespec is a struct. It should be struct timespec . Please modify your code accordingly.

I got this error when trying to compile a working project under Visual Studio 2015 .

The solution was to add HAVE_STRUCT_TIMESPEC to the Preprocessor Definitions.

Through the GUI: Project Properties (pan) > Property Pages (icon) > Configuration Properties > C/C++ > Preprocessor > Preprocessor Definitions > Edit > Add HAVE_STRUCT_TIMESPEC

Or manually: Edit each project file and replace each instance of <PreprocessorDefinitions> (there can be several per file) with something like:

<PreprocessorDefinitions>HAVE_STRUCT_TIMESPEC;WIN32;__GNU_LIBRARY__;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>

NB: I found this answer somewhere on a Github issue , so I'm posting it here.

This issue gave me problems for a while, what I ended up doing was defining struct timespec in my code. (just copied it over, straight from man nanosleep )

#include <time.h>

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

int main(void) {
    struct timespec TS;
    TS.tv_nsec = 1;

    return 0;
}

I know this is an old question but I was having the same problem after upgrading from gcc 6.3 to 7.1. After looking at the changes you have to define _GNU_SOURCE to include struct_timespec.h.

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