【问题标题】:How to solve this Semantic Errors? [duplicate]如何解决这个语义错误? [复制]
【发布时间】:2014-01-08 08:07:36
【问题描述】:
#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 操作系统。

【问题讨论】:

  • 你读过the manual page吗?您缺少手册页中特别提到的头文件。
  • 有人回答:使用 -std=gnu99 成功运行??哪里有那个??
  • 将其添加为gcc中的参数之一。

标签: c linux eclipse gcc compiler-construction


【解决方案1】:

在开头添加#include &lt;time.h&gt;

【讨论】:

  • 我按照你说的做了,但是没用
【解决方案2】:

你需要两件小事。

  1. 如上所述,#include &lt;time.h&gt;

  2. timer_create 需要 feature_test_macro

关于 (2),当您查看 time_create 的手册页时,它会在 SYNOPSIS 区域中告诉您哪些功能需要特定的宏。

所以快速的解决方案是在上面的代码中将以下 定义为第一行,然后在之后的某处添加 time.h 标头。

#define _POSIX_C_SOURCE 199309L

较长的解决方案是阅读feature_test_macro 手册页,因为您会一直遇到这种情况。

顺便说一句,请确保再次链接librt,即-lrt

【讨论】:

  • 非常感谢您的回复。如何以及在何处链接 -lrt ??
  • 我不知道 Eclipse 是如何处理它的,但是您需要将 librt 添加到您的链接库中。我确信某处有一个菜单项可以执行此操作。最终结果将是您的编译命令将类似于 gcc -g -Wall -ofoo foo.c -lrt 等。
猜你喜欢
  • 1970-01-01
  • 2017-03-30
  • 2011-09-04
  • 1970-01-01
  • 2017-08-10
  • 2021-06-25
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
相关资源
最近更新 更多