编译从book中逐字复制的代码会导致编译器错误

时间:2012-02-16 05:23:56

标签: c cocoa new-operator

我正在写一本关于Cocoa和Objective-C的书。我跟着书练习,我确信我编写的代码与书中的代码完全一样。但是,编译代码时出现编译器错误。即使我从书籍PDF中复制并粘贴它,我仍然会遇到编译错误。

这是命令行和输出:

-MacBook-Pro:ch03 CauldronPoint$ gcc SongTest2.c Song2.c -o SongTest
Song2.c:12: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before     
‘createSong’
Song2.c:20: error: expected ‘)’ before ‘theSong’

以下是代码:

//
//  Song2.h
//  

#ifndef _Song2_h
#define _Song2_h

typedef struct {
    char* title;
    int lengthInSeconds;
    int yearRecorded;
} Song;

Song createSong ( char* title, int length, int year );
void displaySong ( Song theSong );

#endif

//
//  Song2.c
//

#include <stdio.h>

Song createSong (char* title, int length, int year) {
    Song mySong;
    mySong.lengthInSeconds = length;
    mySong.yearRecorded = year;
    mySong.title = title;
    displaySong (mySong);
    return mySong;
}
void displaySong (Song theSong) {
    printf ("'%s' is %i seconds long ", theSong.title, theSong.lengthInSeconds);
    printf ("and was recorded in %i\n", theSong.yearRecorded);
}

//
//  SongTest2.c
//  

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

main () {
    Song allSongs[3];
    allSongs[0] = createSong ( "Hey Jude", 210, 2004 );
    allSongs[1] = createSong ( "Jambi", 256, 1992 );
    allSongs[2] = createSong ( "Lightning Crashes", 223, 1997 );
}

任何人都有任何关于如何在没有错误的情况下使其成为complile的想法?

1 个答案:

答案 0 :(得分:2)

您需要在Song2.h中加入标题文件Song2.c 编译器抱怨,因为它不理解Song的类型。

//
//  Song2.c
//

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