Reputation: 129
I am trying to learn how to separate C code into multiple files, but I am running into an error when doing so.
Relevant code (separated by file):
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;
}
When I compile this code, I get this:
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");
^
There is obviously more code than this (will post if requested), but every other part of the code seems to work fine except this snippets. Also, when I put the code from my "main.c" file and "list.c" into the same file the the code works fine.
Any help is appreciated!
Upvotes: 0
Views: 157
Reputation: 206707
You need to add a declaration for install
in ex6.h
. Something like:
extern struct nlist *install(char *name, char *defn);
Without a declaration, the assumed return values of functions are int
. The compiler complains because the type of np1
is struct nlist*
and it tries to assign an int
to np1
.
When you provide the declaration, it knows the return type of install
is struct nlist*
. Hence, it is OK to assign the return value of install
to np1
.
Upvotes: 0
Reputation: 311078
The compilation unit with main does not see the declaration of function install
. So the compiler supposes that the function by default has return type int
and that in this statement
np1 = install("This", "That");
.
a value of type int
is assigned to pointer to the structure.
You should include the function declaration in header "ex6.h" because the function is used in more than one compilation unit.
Upvotes: 0
Reputation: 111349
You're missing a declaration of the install function in the header file. This makes the compiler assume it returns int
rather than a pointer, which causes this warning. Add to ex6.h:
struct nlist *install(char *name, char *defn);
Upvotes: 2