无效使用未定义的类型和未知的存储大小

问题描述

我正在尝试将某些功能移到c项目中的单独文件中。

我用{p>制作了util.h文件

#ifndef _UTIL_H
#define _UTIL_H

#include <signal.h>
#include <termios.h>
#include <time.h>

...

extern struct timeval tv1,tv2,dtv;

void time_start();

long time_stop();

然后我用{p>制作了util.c文件

#include "util.h"

...
struct timeval tv1,dtv;

void time_start() { gettimeofday(&tv1,&timezone); }

long time_stop()
{
    gettimeofday(&tv2,&timezone);
    dtv.tv_sec = tv2.tv_sec - tv1.tv_sec;
...

在我拥有的cmake中

add_executable(mpptd mpptd.c util.c)

在编译过程中出现以下错误

[build] ../settings/daemons/util.c: In function ‘time_stop’:
[build] ../settings/daemons/util.c:14:8: error: invalid use of undefined type ‘struct timeval’
[build]      dtv.tv_sec = tv2.tv_sec - tv1.tv_sec;
[build]         ^

[build] ../settings/daemons/util.c: At top level:
[build] ../settings/daemons/util.c:7:16: error: storage size of ‘tv1’ isn’t known
[build]  struct timeval tv1,dtv;
[build]                 ^~~

这里可能有什么问题?为什么“存储大小”错误晚于“未定义类型”错误?谁不早点去?

解决方法

struct timeval在sys / time.h中定义。您需要将其包括在内。

#ifndef _UTIL_H
#define _UTIL_H

#include <signal.h>
#include <termios.h>
#include <time.h>
#include <sys/time.h>

...
,

结构定义(带有struct { .. }的部分)对于使用该结构进行编码必须是可见的。只需使用该结构将该部分放在代码可见的标头中,然后包含该标头即可。

否则,该结构最终作为不完整类型的前向声明。不完整的类型没有大小,因此存在密码错误。

在这种情况下,您似乎正在使用某些非标准,非POSIX(或可能已过时的POSIX?)库。严格的编译器(例如-std=c11 -pedantic-errors模式下的gcc)不允许在标准标头中包含非标准的废话,因此您必须单独包含特定的非标准标头,而在{{ 1}}。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...