2014-12-19 23 views
-2

當我嘗試編譯我得到這個:爲什麼GCC不能在頭文件中看到函數?

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的新手,所以我確信它很簡單。

+0

GCC看到的聲明,但如果是這些功能的定義是什麼?這是鏈接器找不到的。 – Leiaz

+0

大寫事宜。你爲什麼要提供你自己的錯誤大寫的原型?使用系統標題中的標記,鏈接程序將能夠在系統庫中找到相應的符號。 –

+0

@Leiaz啊謝謝你 – user2892857

回答

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 
相關問題