繁体   English   中英

我不明白为什么编译器给我这个代码的错误

[英]I don't understand why compiler is giving me error with this code

我有以下C代码,对我来说看起来非常正确。 但是,clang编译器(实际上是gcc或任何其他C编译器)也不这么认为。

typedef struct
{
    struct timeval td_start;
    struct timeval td_end;
} Timer;

void startTimer( struct Timer* ptimer ) 
{
    gettimeofday( &(ptimer->td_start), NULL );
}

void stopTimer( struct Timer* ptimer ) 
{
    gettimeofday( &(ptimer->td_end), NULL );
}

编译器提供以下警告和错误消息。 知道这里有什么问题吗?

./timing.h:14:25: warning: declaration of 'struct Timer' will not be visible
      outside of this function [-Wvisibility]
void startTimer( struct Timer* ptimer )
                        ^
./timing.h:16:27: error: incomplete definition of type 'struct Timer'
    gettimeofday( &(ptimer->td_start), NULL );
                    ~~~~~~^
./timing.h:14:25: note: forward declaration of 'struct Timer'
void startTimer( struct Timer* ptimer )
                        ^
./timing.h:19:24: warning: declaration of 'struct Timer' will not be visible
      outside of this function [-Wvisibility]
void stopTimer( struct Timer* ptimer )
                       ^
./timing.h:21:27: error: incomplete definition of type 'struct Timer'
    gettimeofday( &(ptimer->td_end), NULL );
                    ~~~~~~^
./timing.h:19:24: note: forward declaration of 'struct Timer'
void stopTimer( struct Timer* ptimer )

拆下struct关键字(这是没有必要的,因为你已经typedef版的结构):

void startTimer( Timer* ptimer ) 
{
  ...

void stopTimer( Timer* ptimer ) 
{
  ...

或者,删除typedef

struct Timer
{
    struct timeval td_start;
    struct timeval td_end;
};

void startTimer( struct Timer* ptimer ) 
{
  ...

void stopTimer( struct Timer* ptimer ) 
{
  ...

有关更多信息,请参阅为什么我们应该在C中经常键入一个结构?

不管你

struct Timer
{
    struct timeval td_start;
    struct timeval td_end;
};

void startTimer( struct Timer* ptimer ) 
{
    gettimeofday( &(ptimer->td_start), NULL );
}

或者您

typedef struct
{
    struct timeval td_start;
    struct timeval td_end;
} Timer;

void startTimer( Timer* ptimer ) 
{
    gettimeofday( &(ptimer->td_start), NULL );
}

但不要混淆。

您创建了一个名为Timer的类型,只需在函数参数之前删除单词struct,例如:

void startTimer( Timer* ptimer ) 
{
    gettimeofday( &(ptimer->td_start), NULL );
}

错误的原因是,当你到达这里时

void startTimer( struct Timer* ptimer ) 

范围内没有struct Timer (只是匿名结构的typedef)。 因此,编译器认为您要声明一个类型struct Timer并使用指向它的指针作为参数。

实际上这样做不会有用,因为类型只能在函数内部显示。 这将使从函数外部传递参数几乎不可能。

所以编译器说,虽然语言可能允许,但这看起来不是一个好主意!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM