2014-02-26 55 views
0

你好,我對編程世界是全新的,我試圖在網上學習哈佛的CS50課程。 在製作我的「Hello World」程序時,我下載了'cs50.h'來定義GetStringstring(至少我認爲)。所以這是我寫的代碼:C - cs50.h GetString錯誤

file.c:

#include "cs50.h" 
#include <stdio.h> 

int main(int argc, string argv[]) 
{ 
    string name; 
    printf("Enter your name: "); 
    name = GetString(); 
    printf("Hello, %s\n", name); 
} 

然而,每當我試圖make file,出現這種情況:

cc  file.c -o file 
Undefined symbols for architecture x86_64: 
"_GetString", referenced from: 
    _main in file-JvqYUC.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make: *** [file] Error 1 

這裏是對cs50.h鏈接文件,如果它可以幫助:http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.h

我想知道爲什麼我得到這個錯誤,我該如何解決它。請幫忙。

+0

此的更多信息,C,不C++('string'是一個typedef,不'的std :: string')。請僅標記適當的語言(C和C++ *不同*)。刪除C++標籤。 – crashmstr

+0

'cc file.c cs50.c -o file'或'cc file.c cs50.o -o file' – BLUEPIXY

回答

5

看來你忘了下載和鏈接到從http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.c

的* .h通常只包含聲明項目cs50.c文件。 * .c(對於C)和* .cpp(對於C++)包含實現。

有一個從這個類GetSting功能實現:

string GetString(void) 
{ 
    // growable buffer for chars 
    string buffer = NULL; 

    // capacity of buffer 
    unsigned int capacity = 0; 

    // number of chars actually in buffer 
    unsigned int n = 0; 

    // character read or EOF 
    int c; 

    // iteratively get chars from standard input 
    while ((c = fgetc(stdin)) != '\n' && c != EOF) 
    { 
     // grow buffer if necessary 
     if (n + 1 > capacity) 
     { 
      // determine new capacity: start at 32 then double 
      if (capacity == 0) 
       capacity = 32; 
      else if (capacity <= (UINT_MAX/2)) 
       capacity *= 2; 
      else 
      { 
       free(buffer); 
       return NULL; 
      } 

      // extend buffer's capacity 
      string temp = realloc(buffer, capacity * sizeof(char)); 
      if (temp == NULL) 
      { 
       free(buffer); 
       return NULL; 
      } 
      buffer = temp; 
     } 

     // append current character to buffer 
     buffer[n++] = c; 
    } 

    // return NULL if user provided no input 
    if (n == 0 && c == EOF) 
     return NULL; 

    // minimize buffer 
    string minimal = malloc((n + 1) * sizeof(char)); 
    strncpy(minimal, buffer, n); 
    free(buffer); 

    // terminate string 
    minimal[n] = '\0'; 

    // return string 
    return minimal; 
} 
+0

我的回答有用嗎?如果是 - 請接受它。 – Avt

+0

因此,對於我的程序工作,我需要'#include'cs50.c? – user3357419

+0

不包括!你應該把它添加到你的項目!如果您使用的是一些IDE(MS Visual Studio,Xcode,Eclipse ...其中包含數百種IDE),則始終可以通過菜單「添加文件到項目」。如果你正在使用make文件,你應該在make文件中注意到這個文件。 – Avt

0

看看你的第一個包含語句。您正在使用「」代替<>。

+1

這也是他應該*使用的東西; '<>'在這裏使用幾乎肯定是錯誤的。 –

0

在帶有CS50課程的視頻中,教師使用插入符號(<>)而不是引號(「」)。

0

對於任何參加CS50課程的學生,不希望每次都粘貼.c代碼,您還可以在編譯時鏈接CS50代碼。

地點cs50.h和在同一目錄中file.c cs50.c,然後鍵入在命令行以下操作:

clang file.c -lcs50 -o <file name> 

的「-L」的鏈接cs50.c和CS50 .h文件到你的c文件(編譯到目標文件後),「-o」指定編譯輸出的位置。

在此here