2011-03-24 104 views
0

我在学习结构,分别在.h和.c文件中有下面的代码。结构不编译?

typedef struct{ 
    int lengthOfSong; 
    int yearRecorded; 
} Song; 

Song makeSong (int length, int year); 
void displaySong(Song theSong); 

.C:

Song makeSong(int length, int year){ 
    Song newSong; 
    newSong.lengthOfSong = length; 
    newSong.yearRecorded = year; 

    displaySong(newSong); 

    return newSong; 
} 

void displaySong(Song theSong){ 
    printf("This is the length of the song: %i \n This is the year recorded: %i", theSong.lengthOfSong, theSong.yearRecorded); 
} 

出于某种原因,我发现了错误:song.c:1:错误:预期 '=', '', ';',“ASM '或' “前 'makeSong' song.c:11:错误:预期 '属性)theSong '

我是不是做错了什么' 前'?

编辑主(其他功能已经工作):

#include <stdio.h> 
#include "math_functions.h" 
#include "song.h" 

main(){ 
    int differ = difference(10, 5); 
    int thesum = sum(3, 7); 
    printf("differnece: %i, sum: %i \n", differ, thesum); 
    Song theSong = makeSong(5, 8); 

} 
+3

难道你'#包括 “song.h”'? – 2011-03-24 21:55:36

+0

是的。见上面的主要部分。 (已编辑) – locoboy 2011-03-24 21:59:09

+1

您是否在.c文件中包含'#include“song.h”',其中包含'宋makeSong(int length,int year){'?根据编译器的错误信息,看起来不是,因为引用的行是第一行。 – Vlad 2011-03-24 22:04:14

回答

4

displaySong需要一个参数theSong,你正在尝试使用newSong

您还可以从song.c需要#include "song.h" - 错误消息看起来像你跳过的。

+2

作为一个附注,请使用'宋歌',而不是'宋theSong'。代码中的文章很难看。 – alternative 2011-03-24 21:59:14

+0

请注意,编译器已在第1行报告错误。顺便说一句,这证明.c文件不包含#include :) – Vlad 2011-03-24 22:02:10

+0

虽然这是真的,但这不是问题。我解决了这个问题,但我仍然遇到同样的问题。 – locoboy 2011-03-24 22:02:22

-1

编辑:搞砸typedef在我以前的答案:

typedef struct NAME1 { 
    ... 
} NAME2; 

NAME1名的结构,NAME2的explizit类型struct NAME1。 现在NAME1不能没有struct用于C,NAME2可以:

struct NAME1 myvar1; 
NAME2 myvar2; 

你得到这个问题的原因Song不识别为一个变量的类型(无前struct关键字)。

+0

-1:不正确。匿名结构的typedef不是无效的。 – Erik 2011-03-24 22:01:05

+0

它可以:http://ideone.com/0eBHf – Vlad 2011-03-24 22:01:43

+0

是的,搞砸了typedef,现在应该修复。 – Mario 2011-03-24 22:02:53

2

您需要在.c文件中#include "song.h"其中makeSong()displaySong()被定义。否则,编译器不知道如何创建Song类型的对象。

+0

我做到了。看到上面的主要。 – locoboy 2011-03-24 22:09:19

+1

@ cfarm54:不是主要的。你还需要包含上面的'宋makeSong(int长度,int年){'。你需要包含在** ALL ** .c文件中。 – pmg 2011-03-24 22:10:55

+0

我想很多人都这样说,但我有点困惑,我需要把#include也许。似乎我在我的main.c中找到了正确的地方,但是也许我需要把它放在其他地方呢? – locoboy 2011-03-24 22:14:38

1

随着之前的更正,仍然出现错误,因为程序在这两个头文件中都不包括song.h。源文件需要包括song.h(即在main.csong.c中,猜测您已经命名了源文件)。此外 -

Song makeSong(int length, int year){ 
    Song newSong; 
    newSong.lengthOfSong = length; 
    newSong.yearRecorded = year; 

    displaySong(newSong); 

    return newSong; 
} 

可以简化为 -

Song makeSong(int length, int year){ 

    Song newSong = { length, year } ; 

    displaySong(newSong); 

    return newSong; 
}