如何解决这个语义错误? [重复]

问题描述 投票:0回答:2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>

void my_handler ( timer_t timerid)
{
    printf("\nHello World\n");
}

int main()
{

 // declare some variables

 timer_t timerid;
 struct itimerspec itime;
 struct sigevent sevp;

 // initalize the sigevent variable
 // the memset is necessary to avoid segmentation faults 
 memset (&sevp, 0, sizeof (struct sigevent));
  sevp.sigev_notify=SIGEV_THREAD;
  sevp.sigev_notify_function=(void *)my_handler;


  timer_create (CLOCK_REALTIME, &sevp, &timerid);
  // initialize the timer specification
 // currently the offset and the period is 5 seconds  // you have to adjust this to your actual needs
  itime.it_value.tv_sec = 5;
  itime.it_value.tv_nsec = 0;
  itime.it_interval.tv_sec = 5;
  itime.it_interval.tv_nsec = 0;

 // create the timer
 timer_settime (timerid, 0, &itime, NULL);

 // this loop has to be adapted, so that the program ends after some time  while(1){
 // sleep(100);

}

错误:

Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/new.d" -MT"src/new.d" -o "src/new.o"  In 'CLOCK_REALTIME' undeclared (first use in this function)  
Field 'tv_nsec' could not be resolved       Semantic Error
Field 'tv_nsec' could not be resolved       Semantic Error
Field 'tv_sec' could not be resolved        Semantic Error
Field 'tv_sec' could not be resolved        Semantic Error
storage size of 'itime' isn't known     C/C++ Problem

我正在使用带有 Eclipse IDE 的 Linux 操作系统。

c linux eclipse gcc
2个回答
2
投票

在开头添加

#include <time.h>


0
投票

你需要两件小东西。

  1. 如上所述,

    #include <time.h>

  2. timer_create
    需要一个feature_test_macro

关于 (2),当您查看

time_create
的手册页时,在概要区域中,它会告诉您哪些函数需要特定的宏。

因此,快速解决方案是将以下 定义为上面代码中的第一行,然后在其后的某处添加

time.h
标头。

#define _POSIX_C_SOURCE 199309L

更长的解决方案是阅读

feature_test_macro
手册页,因为你会一直遇到这种事情。

顺便说一句,请确保再次链接

librt
,即
-lrt

© www.soinside.com 2019 - 2024. All rights reserved.