问题描述
在最近的一个项目中,过去一个小时左右我一直在努力修复这个语法错误; gcc 抱怨它所说的两个相同类型的对象之间的类型不匹配:
../../devices/timer.c: In function ‘timer_interrupt’:
../../devices/timer.c:181:19: warning: passing argument 1 of ‘thread_foreach’ from incompatible pointer type [-Wincompatible-pointer-types]
181 | thread_foreach (timer_check,NULL);
| ^~~~~~~~~~~
| |
| void (*)(struct thread *,void *)
In file included from ../../devices/timer.c:9:
../../threads/thread.h:134:42: note: expected ‘void (*)(struct thread *,void *)’ but argument is of type ‘void (*)(struct thread *,void *)’
134 | void thread_foreach (thread_action_func *func,void *aux);
| ~~~~~~~~~~~~~~~~~~~~^~~~
../../devices/timer.c: At top level:
../../devices/timer.c:185:1: error: conflicting types for ‘timer_check’
185 | timer_check (struct thread *thread,void *aux) {
| ^~~~~~~~~~~
In file included from ../../devices/timer.c:1:
../../devices/timer.h:29:6: note: prevIoUs declaration of ‘timer_check’ was here
29 | void timer_check(struct thread *thread,void *aux);
| ^~~~~~~~~~~
我尝试过添加/删除引用或取消引用运算符、更改所涉及函数的一些签名以使其与我在网上看到的示例更相似。
例如,我尝试将 thread_action_func
的签名从 typedef void thread_action_func
更改为 typedef void (*thread_action_func)
,并将函数参数中类型的使用从 thread_action_func *
更改为 {{ 1}},但它要么抱怨传递的类型不再是函数或函数指针,要么抛出相同类型不匹配的相同错误。
我还尝试在函数 thread_action_func
调用 thread_foreach
作为参数的位置前面添加一个 address-of,例如 timer_check
,但错误仍然与最初相同。
相关的函数/原型/类型定义是:
thread.h:
thread_foreach(&timer_check,...)
thread.c:
struct thread
{
...
int64_t block_ticks;
...
};
typedef void thread_action_func (struct thread *t,void *aux);
void thread_foreach (thread_action_func *func,void *aux);
定时器.h:
void
thread_foreach (thread_action_func *func,void *aux)
{
struct list_elem *e;
ASSERT (intr_get_level () == INTR_OFF);
for (e = list_begin (&all_list); e != list_end (&all_list);
e = list_next (e))
{
struct thread *t = list_entry (e,struct thread,allelem);
func (t,aux);
}
}
timer.c:
void timer_check(struct thread *thread,void *aux);
我通过搜索此类问题找到的所有结果仅在一个方面或另一个方面相似,不够接近而没有用,例如显示函数指针的示例或指向整数或字符的指针的错误。
我猜这是一些明显的语法错误,我太沮丧而没有注意到,但目前我无法真正清楚地看到可能导致问题的原因。
解决方法
当您在不同范围内重新定义 struct
标记时会发生此错误。
您尚未提供 Minimal Reproducible Example,因此我们无法确定错误在哪里,但可能是 timer.h
中的此代码:
void timer_check(struct thread *thread,void *aux);
使用函数原型作用域声明 struct thread
。这仅在函数声明期间定义了 struct
类型,这通常是无用的。
然后,在 timer.c
中,大概您包含一些声明 thread_unblock
的标头,并且在包含 timer.h
之后(如果是)包含此标头。该标头声明了自己的 struct thread
并在 thread_unblock
的声明中使用它。
由于函数 timer_check
的参数类型与 thread_unblock
中使用的类型不同,编译器报告它们具有不兼容的类型,即使它们具有相同的名称(来自不同的范围)。
要解决此问题,timer.h
应在声明 struct thread
之前包含声明 timer_check
的标头。然后参数声明 struct thread *thread
将引用已经可见的结构类型,而不是定义一个新的。
为了说明,这里是重现错误的代码:
// struct thread; // Uncommenting this line will elimninate the error.
void foo(struct thread *);
void bar(void (*)(struct thread *));
void baz(void)
{
bar(&foo);
}