头文件定义结构体,fatal error LNK1169: 找到一个或多个多重定义的符号

五岳凌峰 五岳凌峰 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
正在学习多文件编译,工程包括1个头文件(stuscore.h)、3个源文件(main.cpp、a1.cpp、a2.cpp)。其代码分别如下

stuscore.h:
#ifndef _STUDENTSCORE_H_
#define _STUDENTSCORE_H_

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

struct student_score
{
char name[10];
int num;
int China;
int Math;
int English;
}score[100];

void save(char*name,int n);
void show(char*name,int n);

#endif


main.cpp:
#include "stuscore.h"

int main()
{
int i,n;
char filename[50];
printf("how many students in your class?\n");
scanf("%d",&n);
printf("please input filename:\n");
scanf("%s",filename);
printf("please input name,number,China,math,English:\n");
for(i=0;i<n;i++)
{
printf("NO%d",i+1);
scanf("%s%d%d%d%d",score[i].name,&score[i].num,&score[i].China,&score[i].Math,&score[i].English);
save(filename,n);
}
show(filename,n);
system("pause");
}


a1.cpp:
#include "stuscore.h"

void save(char*name,int n)
{
FILE *fp;
int i;
if ((fp=fopen(name,"wb"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
for(i=0;i<n;i++)
if(fwrite(&score[i],sizeof(struct student_score),1,fp)!=1)
printf("file write error\n");
fclose(fp);
}


a2.cpp:
#include "stuscore.h"

void show(char*name,int n)
{
int i;
FILE *fp;
if ((fp=fopen(name,"rb"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
for (i=0;i<n;i++)
{
fread(&score[i],sizeof(struct student_score),1,fp);
printf("%-10s%4d%4d%4d%4d\n",score[i].name,score[i].num,score[i].China,score[i].Math,score[i].English);
}
}


运行后报错:
1>a1.obj : error LNK2005: "struct student_score * score" (?score@@3PAUstudent_score@@A) 已经在 main.obj 中定义
1>a2.obj : error LNK2005: "struct student_score * score" (?score@@3PAUstudent_score@@A) 已经在 main.obj 中定义
1>G:\VS2010\mywork\example7\Debug\e170.exe : fatal error LNK1169: 找到一个或多个多重定义的符号

网上搜了很多相似问题,但回答不能完全对应出错情况。希望师兄解答下
...全文
评论 12
收藏 已收藏
分享
返回顶部
五岳凌峰
C语言 70,040 成员 243,237 内容