如何修复sfml c++代码编译错误
How can I fix sfml c++ code compilation error?
我已经创建了2个.cpp文件和2个.header文件
- main.cpp(main.cpp文件(
- main.hpp(主头文件(
- 游戏.cpp
- 游戏.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
,但不要这样做,因为编译器会向您显示大量令人困惑的消息。只是不要这样做,直到你知道预处理器+编译器+链接器是如何协同工作的。
相关文章:
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?