为什么GCC没有在头文件中看到函数?

时间:2014-12-19 22:54:17

标签: header-files reference

当我尝试编译时,我得到了这个:

aero$ gcc hostinfo.c
/tmp/cc2RfYB2.o: In function `main':
hostinfo.c:(.text+0x72): undefined reference to `Gethostbyaddr'
hostinfo.c:(.text+0x8b): undefined reference to `Gethostbyname'
collect2: ld returned 1 exit status

hostinfo.c如下所示:

/* $begin hostinfo */
#include "csapp.h"

int main(int argc, char **argv)
{

...

    if (inet_aton(argv[1], &addr) != 0)
        hostp = Gethostbyaddr((const char *)&addr, sizeof(addr), AF_INET);
    else
        hostp = Gethostbyname(argv[1]);

...

}
/* $end hostinfo */

csapp.h看起来像这样:

/* $begin csapp.h */
#ifndef __CSAPP_H__
#define __CSAPP_H__

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <setjmp.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

...

/* DNS wrappers */
struct hostent *Gethostbyname(const char *name);
struct hostent *Gethostbyaddr(const char *addr, int len, int type);

... 

#endif /* __CSAPP_H__ */
/* $end csapp.h */

hostinfo.c和csapp.h都在同一目录中。我是Unix和gcc的新手,所以我确信这很简单。

2 个答案:

答案 0 :(得分:2)

您需要编译包含这些函数实现的文件,然后将其与调用文件链接:

gcc -c csapp.c                      # This creates csapp.o
gcc -c hostinfo.c                   # This creates hostinfo.o
gcc -o hostinfo hostinfo.o csapp.o  # Link them together, creating executable hostinfo

答案 1 :(得分:0)

我基本上遇到了未定义引用`function_name'的错误

最终通过组合可执行文件中的两个c文件解决了

例如,我有带有columns.h的csv.c和columns.c,所以不是

gcc csv.c -o csv

我用过

gcc csv.c columns.c -o csv