我正在 ray lib 中创建一个游戏,并有一个带有 player 结构的播放器头文件,以使事情井井有条。我收到这个错误,说结构'player'有多个定义。
错误:
/usr/bin/ld: main.o:(.bss+0x0): multiple definition of `player'; player.o:(.bss+0x0): first defined here collect2: error: ld returned 1 exit status
播放器.cpp:
#include <raylib.h>
#include "player.h"
void InitPlayer() {
player.x = 0;
player.y = 0;
player.tint = (Color)RAYWHITE;
player.Frame = 0;
player.FrameWidth = 16;
player.MaxFrames = 3;
player.animation_number = 0;
player.timer = 0.0f;
player.flip = 1;
//Load Texture2D
player.playerTexture = LoadTexture("Sprites/PlayerAll.png");
}
void UpdatePlayer() {
player.timer += GetFrameTime();
if(player.timer >= 0.2f){
player.timer = 0.0f;
player.Frame += 1;
}
if(IsKeyDown(KEY_S)) {
player.animation_number = 16;
player.y += 1;
}else if(IsKeyUp(KEY_S)){
player.animation_number = 0;
}
if(IsKeyDown(KEY_W)){
player.animation_number = 32;
player.y -= 1;
}
if(IsKeyDown(KEY_A)){
player.animation_number = 48;
player.x -= 1;'''
}
if(IsKeyDown(KEY_D)){
player.animation_number = 48;
player.x += 1;
player.flip = -1;
} else {
player.flip = 1;
}
//Clamp frame value
player.Frame = player.Frame % player.MaxFrames;
}
void DrawPlayer() {
DrawTexturePro(player.playerTexture,
Rectangle{player.FrameWidth*player.Frame,(float)player.animation_number,(float)player.flip*16,16},
Rectangle{(float)player.x,(float)player.y,16,16},
Vector2{0,0},0,player.tint);
}
void UnloadPlayer() {
UnloadTexture(player.playerTexture);
}
播放器.cpp:
#ifndef PLAYER_H
#define PLAYER_H
typedef struct Player{
int x, y;
Color tint;
int Frame;
int FrameWidth;
int MaxFrames;
int animation_number;
float timer;
int flip;
Texture2D playerTexture;
}Player;
Player player;
void UnloadPlayer();
void InitPlayer();
void UpdatePlayer();
void DrawPlayer();
#endif
Main:main.cpp'文件基本上调用'player.h'文件中的函数。我在 'main.cpp' 中包含了 'player.h'
如果需要的话,只是为了提供一些额外的信息:我尝试在“播放器”上使用“extern”,但它要求我以奇怪的顺序编译 cpp 文件。在编译并链接对象'player.o'和'main.o'之后,我将'player.cpp'更改为在结构全局变量'player'上具有'extern'并仅编译'player.cpp'而不编译'main。 cpp' 并链接两个对象文件,其中 'main.o' 是旧的。