2012-09-28 59 views
0

嘗試編譯使用結構的C源文件時出現錯誤。 我在Ubuntu 12.04 LTS上使用gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3。獲取初始化C中結構的錯誤

下面是代碼:

/* struct.c: Illustrates structures */ 
#include <stdio.h> 
#include <string.h> 

struct Hitter { 
    char last[16]; 
    char first[11]; 
    int home_runs; 
}; 

int main() { 
    struct Hitter h1 = {"McGwire", "Mark", 70}; 
    struct Hitter h2; 
    strcpy(h2.last, "Sosa"); 
    strcpy(h2.first, "Sammy"); 
    h2.home_runs = h1.home_runs - 4; 
    printf("#1 == {%s, %s, %d}\n", 
      h1.last, h1.first, h1.home_runs); 
    printf("#2 == {%s, %s, %d}\n", 
      h2.last, h2.first, h2.home_runs); 
    return 0; 
} 

,這裏是錯誤:

$ gcc -o struct struct.c 
struct.c: In function `main': 
struct.c:12:9: error: parameter `h1' is initialized 
struct.c:14:2: error: expected declaration specifiers before `strcpy' 
struct.c:15:2: error: expected declaration specifiers before `strcpy' 
struct.c:16:2: error: expected declaration specifiers before `h2' 
struct.c:18:2: error: expected declaration specifiers before `printf' 
struct.c:21:2: error: expected declaration specifiers before `printf' 
struct.c:23:2: error: expected declaration specifiers before `return' 
struct.c:24:1: error: expected declaration specifiers before `}' token 
struct.c:13:16: error: declaration for parameter `h2' but no such parameter 
struct.c:12:16: error: declaration for parameter `h1' but no such parameter 
struct.c:24:1: error: expected `{' at end of input 

上面的代碼是從CD培訓課程 「用C思考」 由Chuck佳佳。我知道這是一張非常舊的CD,我相信結構的語法必須改變,但我不知道現在會是什麼樣子。感謝您的幫助。 謝謝

+2

乍一看這段代碼對我來說似乎還行。 –

+1

@Mat似乎GCC的版本號是負數... – 2012-09-28 15:33:53

+0

奇怪的是,我使用gcc 4.5.2,它編譯得很好。 – Tudor

回答

1

一旦我有類似的情況下,它試圖編譯的文件有不正確的行結束。例如,從磁盤獲取的文件可能具有CR + LF作爲行尾,而只有LF是預期的。這可以通過在大多數文本編輯器中選擇顯示不可見字符來發現。

+0

這幫助我在Windows中編輯和在Linux中編譯時更改我的編輯器設置。謝謝。 – cstricklan