c++sfmllnk2005

I keep on having an LNK2005 error while programming in c++ I can't seem to figure out what is the issue


I can't figure out what these two errors are. LNK2005 "public: bool __thiscall Bird::move(void)" (?move@Bird@@QAE_NXZ) already defined in Bird.obj SFML-Game E:\Visual Studio Projects\SFML-Game\SFML-Game\main.obj

LNK1169 one or more multiply defined symbols found  SFML-Game   E:\Visual Studio Projects\SFML-Game\Debug\SFML-Game.exe     

-------Bird.h------

#pragma once

#include <iostream>
#include <SFML/Window/Keyboard.hpp>

class Bird
{
public:

    bool move();

private:
    int gravity;
    int velocity;

};

------Bird.cpp------

#pragma once
#include "Bird.h"

bool Bird::move() {

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
        //TODO: Set Gravity to -1
        std::cout << "..";

    }

    return true;
}

-----main.cpp-----

#include <SFML/Graphics.hpp>
#include <SFML/Window/Keyboard.hpp>
#include "Bird.cpp"
#include <random>
#include <iostream>

int main()
{
    //Set the window to 800 by 600 pixels
    sf::RenderWindow window(sf::VideoMode(600, 800), "Flappy Dot");
    //Make a circle that is Blue 
    sf::CircleShape shape(20.f);
    shape.setFillColor(sf::Color(255,255,255,100));
    //While the window is open the constantly do these tasks
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }



        window.clear(sf::Color(255,255,255,100));
        window.draw(shape);
        window.display();
    }

    return 0;
}

Solution

  • This line:

    #include "Bird.cpp"
    

    effectively copy-pastes the entire Bird.cpp into main.cpp. Assuming Bird.cpp is also part of your VS project, it means its contents will get compiled and linked in twice: once as the file itself, and once the copy included in main.cpp. This will of course lead to multiple-definition errors like the one you're seeing.

    There's hardly ever need to #include one .cpp file inside anohter, and it should most definitely not be done when both files are compiled normally and linked together. Simply replace that line in main.cpp with:

    #include "Bird.h"