简体   繁体   English

错误:函数的类型冲突

[英]Error: conflicting types for a function

Below is the insertItem() declaration in list.h , 以下是list.hinsertItem()声明,

void insertItem(List *, void *newItem);

Below is the insertItem() declaration in tree.h , 以下是tree.hinsertItem()声明,

void insertItem(Tree *, void *item);


Below is the Tree abstraction, that re-use List abstraction, by saying #include"list/list.h" 下面是Tree抽象,通过说#include"list/list.h"重用List抽象。

#ifndef TREE_H /* Header guard */
#define TREE_H

#include"list/list.h"

.....

void insertItem(Tree *, void *item);
....

#endif

On compilation: 关于编译:

gcc -Wall -g -I. -DARRAY -DMULTI_WALK ./list/*.c ./tree/*.c testTree.c -o testTree

Below is the error: 下面是错误:

./tree/tree.h:50:6: error: conflicting types for ‘insertItem’
 void insertItem(Tree *, void *item);
      ^
In file included from ./tree/tree.h:8:0,
                 from ./tree/multiWalkImpl.c:2:
./list/list.h:35:7: note: previous declaration of ‘insertItem’ was here
  void insertItem(List *, void *newItem);

What is the nature of problem? 问题的本质是什么? Because insertItem() in tree.h & list.h have different parameter types. 因为tree.hlist.h insertItem()具有不同的参数类型。

How to resolve this problem? 如何解决这个问题?

Since C has no function overloading, conflicts like this are usually solved by adding a prefix describing the differing parameter. 由于C没有函数重载,因此通常可以通过添加描述不同参数的前缀来解决此类冲突。

eg List_insertItem and Tree_insertItem . 例如List_insertItemTree_insertItem


Note that in real code, this kind of namespacing prefixes should be added before any such conflicts arise, because there's no way of knowing beforehand what function names the user code is using. 请注意,在实际代码中,应在此类冲突发生之前添加这种命名空间前缀,因为无法事先知道用户代码使用的是什么函数名称。 This saves the trouble of breaking existing code when the names are later changed. 这样可以避免以后更改名称时破坏现有代码的麻烦。

In your case you could use the _Generic operator. 在您的情况下,您可以使用_Generic运算符。

First you need to change the names of your container functions. 首先,您需要更改容器函数的名称。 Preferably to something like: list_insertItem, tree_insertItem, etc.. 最好是这样的:list_insertItem,tree_insertItem等。

Then use generic: 然后使用泛型:

#define insertItem( object , item )    _Generic( object ,                 \
                                                 Tree*: tree_insertItem , \
                                                 List*: list_insertItem )( object , item )

This macro definition must see definitions of both types and both function so your could put it into a common header that includes both headers for containers, include that header in your code, and use the generic macro function. 此宏定义必须同时看到两种类型的定义,并且必须同时具有两种功能,因此您可以将其放入包含容器的两个标头的通用标头中,并在代码中包含该标头,然后使用通用宏功能。

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

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