C语言中编译器误将结构体返回函数识别为int返回的问题
问题原因
在C语言中,调用未提前声明/定义的函数时,编译器会默认该函数返回值为int类型。你的main.c调用constructPlayer前,没有声明这个函数的原型,导致编译器误判其返回值为int,和实际的struct ch类型不匹配,从而报错。
解决方案
有两种规范的解决方式:
方法一:在头文件中添加函数原型(推荐)
修改champ.h,在结构体声明后加入constructPlayer的函数原型,让所有引入该头文件的代码都能获取函数的正确接口:
#ifndef CHAMP_H #define CHAMP_H struct ch { //champion incarné par le joueur char name[30]; //stats int lvl; int pv; // health bar int ad; // attack damage int ap; // magic damage int arm; // armor int gld; // gold int crit; int itm[5]; // item register int abt[5]; // ability register int spd; // speed -> utile pour fightMech.c/dodge (+ rapide = + de dodge) int class; // type de champion, (créer un registre avec sorts/stats de base ?? }; // 新增constructPlayer函数原型 struct ch constructPlayer(char nameIn[20]); #endif
方法二:在main.c中提前声明函数
在main.c的头文件引入区之后,main函数之前,添加函数声明:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include "profile/champ.h" // 提前声明constructPlayer函数 struct ch constructPlayer(char nameIn[20]); int main() { // 原有代码... }
额外注意事项
- 编译时需将
player.c和main.c一起编译,例如GCC命令:gcc main.c player.c -o game,否则会出现链接错误。 - 代码中
start()、descS0()等其他未声明的函数,也会触发同样的默认int返回值问题,需要用同样的方式补充原型声明。
内容的提问来源于stack exchange,提问作者Naël
相关产品推荐
相关产品推荐

