结构不编译?

时间:2011-03-24 21:53:45

标签: c struct

我正在尝试学习结构,并分别在.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'之前

我做错了吗?

编辑main(其他功能已经在运行):

   #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);

}

4 个答案:

答案 0 :(得分:4)

displaySong采用 theSong 参数,您尝试使用 newSong

您还需要#include "song.h"中的song.c - 错误消息看起来就是您跳过了。

答案 1 :(得分:2)

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

答案 2 :(得分: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;
}

答案 3 :(得分:-1)

编辑:在我之前的回答中隐藏了typedef

typedef struct NAME1 {
    ...
} NAME2;

NAME1为结构命名,NAME2为探索类型struct NAME1。 现在NAME1在C中没有struct时无法使用,NAME2可以:

struct NAME1 myvar1;
NAME2 myvar2;

您遇到的问题原因Song无法识别为变量类型(之前没有struct关键字)。