2014-07-20 45 views
0

我想了解如何将C代码分离为多个文件,但这样做时我遇到了错误。C - 跨多个文件返回结构指针时出错

相关的代码(由文件分隔):

ex6.h:

#ifndef __ex6_h__ 
#define __ex6_h__ 

struct nlist { /* table entry: */ 
    struct nlist *next; /* next entry in chain */ 
    char *name; /* defined name */ 
    char *defn; /* replacement text */ 
}; 

#endif 

list.c:

#include "ex6.h" 

struct nlist *install(char *name, char *defn) 
{ 
    struct nlist *np; 
    unsigned hashval; 

    if ((np = lookup(name)) == NULL) { /* not found */ 
     np = (struct nlist *) malloc(sizeof(*np)); 
     if (np == NULL || (np->name = strdup(name) == NULL) 
      return NULL; 
     hashval = hash(name); 
     np->next = hashtab[hashval]; 
     hashtab[hashval] = np; 
    } else /* already there */ 
     free((void *) np->defn); /*free previous defn */ 
    if ((np->defn = strdup(defn)) == NULL) 
     return NULL; 
    return np; 
} 

main.c中:

#include "ex6.h" 

int main (int argc, char* argv[]) 
{ 
    struct nlist *np1; 

    np1 = install("This", "That"); 

    return 0; 
} 

当我编译这个代码,我得到这个:

cc -g main.c list.c -o main 
main.c: In function ‘main’: 
main.c:10:6: warning: assignment makes pointer from integer without a cast [enabled by default] 
    np1 = install("This", "That"); 
^

显然有更多的代码比这个(如果需要,会发布),但代码的其他部分似乎工作正常,除了这个片段。另外,当我把我的“main.c”文件和“list.c”中的代码放到同一个文件中时,代码工作正常。

任何帮助表示赞赏!

回答

2

您错过了头文件中安装函数的声明。这会使编译器假定它返回int而不是指针,这会导致此警告。添加到ex6.h:

struct nlist *install(char *name, char *defn); 
+0

这肯定会有所帮助。谢谢。 – upgrayedd

0

带main的编译单元没有看到函数install的声明。因此,编译器假定该函数默认返回类型为int,并且在此语句中为

np1 = install("This", "That");

类型为int的值被分配给指向该结构的指针。

您应该在头文件“ex6.h”中包含函数声明,因为该函数在多个编译单元中使用。

0

您需要在ex6.h中添加install的声明。喜欢的东西:

extern struct nlist *install(char *name, char *defn); 

如果没有声明,功能的假设返回值是int。编译器抱怨,因为np1的类型是struct nlist*,并且它试图将int指定给np1

当您提供该声明时,它知道install的返回类型为struct nlist*。因此,将返回值install指定为np1即可。