invalid use of undefined type & storage size unknown

≡放荡痞女 提交于 2021-02-05 07:44:28

问题


I am trying to move some functions to separate file in c project.

I made util.h file with

#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();

and I made util.c file with

#include "util.h"

...
struct timeval tv1, tv2, dtv;

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

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

in cmake I have

add_executable(mpptd mpptd.c util.c)

and I get the following errors during compile

[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]         ^

and

[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, tv2, dtv;
[build]                 ^~~

What can be wrong here? Why "storage size" error goes later than "undefined type" error? Whouldn't it go earlier?


回答1:


struct timeval is defined in sys/time.h. You'll need to include that.

#ifndef _UTIL_H
#define _UTIL_H

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

...



回答2:


The struct definition (the part with struct { .. }) must be visible to code using that struct. Simply put that part in a header visible to the code using the struct, then include that header.

Otherwise the struct ends up as a forward declaration, of incomplete type. Incomplete types don't have any size, hence the cryptic errors.

In this case you seem to be using some non-standard, non-POSIX (or possibly obsolete POSIX?) library. Strict compilers (like gcc in -std=c11 -pedantic-errors mode) won't allow non-standard crap in standard headers, so you'll have to include the specific non-standard header separately, the struct won't be found in time.h.



来源:https://stackoverflow.com/questions/64607752/invalid-use-of-undefined-type-storage-size-unknown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!