如何修复sfml c++代码编译错误

How can I fix sfml c++ code compilation error?

本文关键字:编译 错误 代码 c++ 何修复 sfml      更新时间:2023-10-16

我已经创建了2个.cpp文件和2个.header文件

  1. main.cpp(main.cpp文件(
  2. main.hpp(主头文件(
  3. 游戏.cpp
  4. 游戏.hpp

我在game.hp中使用了main.hpp组件

代码:

#include <SFML/Graphics.hpp>
#include <bits/stdc++.h>
#include "Window.hpp"
using namespace std;
class Ship{
public:
Ship();
~Ship();
int ship_x=400-28;
int ship_y=600-55;
sf::Texture ship_texture;
sf::Sprite ship_sprite;
Window *window = new Window();
void Ship_Void(){
if(window->event.type==sf::Event::KeyPressed){
if(window->event.key.code==sf::Keyboard::D){
if(ship_sprite.getPosition().x<=544)
ship_sprite.move(sf::Vector2f(0.04, 0));
}
if(window->event.key.code==sf::Keyboard::A){
if(ship_sprite.getPosition().x>=200)
ship_sprite.move(sf::Vector2f(-0.04, 0));
}
if(window->event.key.code==sf::Keyboard::W){
if(ship_sprite.getPosition().y>=0)
ship_sprite.move(sf::Vector2f(0, -0.04));
}
if(window->event.key.code==sf::Keyboard::S){
if(ship_sprite.getPosition().y<=545)
ship_sprite.move(sf::Vector2f(0, 0.04));
}
}
}
void Keys(){
ship_texture.loadFromFile("images/spaceship.png");
ship_sprite.setTexture(ship_texture);
ship_sprite.setPosition(ship_x, ship_y);
}
};

编译命令:

g++ Window.cpp -o game -lsfml-graphics -lsfml-window -lsfml-system

编译错误:

In file included from Ship.hpp:3,
from Window.cpp:2:
Window.hpp:5:7: error: redefinition of ‘class Window’
5     | class Window{
|       ^~~~~~
In file included from Window.cpp:1:
Window.hpp:5:7: note: previous definition of ‘class Window’
5 | class Window{

请帮助修复此错误!

#include "game.hpp"放在文件main.cpp 的顶部

比方说,您希望在main.cpp中使用您在game.cpp定义的一些其他变量、函数、类或其他标识符。

准则是在头文件中放入您想要在外部使用的东西的声明

因此,如果您有game.cpp的内容(函数有两个定义(:

#include <iostream>
namespace mygame {
void a() { 
std::cout << "A";
}
int b() {
std::cout << "B";
return 1;
}
}

如果您想在main.cpp中使用b(),则在标头game.hpp:中添加b声明

#ifndef GAME_HPP
#define GAME_HPP
int b();
#endif

然后通过将#include "game.hpp"放在main.cpp的顶部,将此标头包含在main.cpp中,从而允许您自由使用b()。所以main.cpp可能看起来像:

#include <iostream>
#include "game.hpp"
int main()
{
std::cout << "MAIN";
mygame::b();
int x = mygame::b(); // remember that b() returns int
}

请注意,game.hpp还包含一些难看的命令。它们不是#include文件本身所必需的,但应用于保护不受多个定义的影响。要了解更多信息,请查找收割台防护

还要注意,从技术上讲,您可以包含源文件game.cpp,而不是game.hpp,但不要这样做,因为编译器会向您显示大量令人困惑的消息。只是不要这样做,直到你知道预处理器+编译器+链接器是如何协同工作的。