简体   繁体   中英

Error: conflicting types for a function

Below is the insertItem() declaration in list.h ,

void insertItem(List *, void *newItem);

Below is the insertItem() declaration in tree.h ,

void insertItem(Tree *, void *item);


Below is the Tree abstraction, that re-use List abstraction, by saying #include"list/list.h"

#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.

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.

eg List_insertItem and Tree_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.

First you need to change the names of your container functions. Preferably to something like: list_insertItem, tree_insertItem, etc..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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