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

标签 c linux gcc clang x86-64

我有以下 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 ) 
{
  ...

有关详细信息,请参阅 Why should we typedef a struct so often in C?

关于c - 我不明白为什么编译器给我这个代码的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10603182/

相关文章:

linux - 为不同的 block 设备使用不同的 Linux I/O 调度器

perl - 虫虫 | perl模块安装噩梦: no cc, gcc可以吗?

c++ - 指针算术编译失败,gcc 说类型转换无效

c++ - undefined symbol 的一般故障排除技术 - gcc

c - 如何从我的 c 扩展访问 ruby​​ 数组?

c - 插入排序进行到一半时打印数组的内容

linux - 与位置无关的可执行文件和 ptrace

linux - linux fsync 会同步文件的 xattr 吗?

c - atof() 没有获取 symbian 中的全部值

python - 将C公式转换为Python