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

pyt*_*nic 10 c linux gcc x86-64 clang

我有以下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 );
}
Run Code Online (Sandbox Code Playgroud)

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

./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 )
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 16

删除struct关键字(因为您已经typedef编辑了结构,所以不需要它):

void startTimer( Timer* ptimer ) 
{
  ...

void stopTimer( Timer* ptimer ) 
{
  ...
Run Code Online (Sandbox Code Playgroud)

或者,删除typedef:

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

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

void stopTimer( struct Timer* ptimer ) 
{
  ...
Run Code Online (Sandbox Code Playgroud)

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

  • 更好的解决方案:不要使用typedef! (2认同)