首页 > 解决方案 > Visual C++ LNK2005 错误:已在 filename.obj 中定义变量名(使用 SFML)

问题描述

我的项目中有 3 个文件,main.cpp、Globals.h 和 Globals.cpp:

主文件

#include "Globals.h"

int main()
{
if (setup())return 1;//If setup fails terminate the program
CenterOrigin(playerSprite);
while (window.isOpen())
    {
    deltaTime = deltaClock.restart().asSeconds();
    while (window.pollEvent(ev))
       {
        if (ev.type == sf::Event::Closed)window.close();
       }
    float rotSpeed = 5;

    window.clear(sf::Color(12, 14, 12, 0.9 * 255));

    window.display();
    }
return 0;
}

全局文件

#pragma once

#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>  
#include <SFML/System.hpp>

#define TITLE "Belty McBelth"
#define WIDTH 1280
#define HEIGHT 720

sf::RenderWindow window;
sf::Font font; 
sf::Event ev; 
sf::Texture playerTex; 
sf::Sprite playerSprite; 
sf::Texture tieTex; 
sf::Sprite tieSprite; 

sf::Clock deltaClock;
float deltaTime; //Time since last frame in seconds

int setup();
void CenterOrigin(sf::Sprite & t);

全局变量.cpp

#include "Globals.h"

int setup()
{
    window.create(sf::VideoMode(WIDTH, HEIGHT), "Belty McBelth", sf::Style::Close);
    if (!font.loadFromFile("../comic.ttf"))return 1;
    if (!playerTex.loadFromFile("../PLAYER.png"))return 1;
    playerSprite = sf::Sprite(playerTex);
    std::cout << "Setup completed without errors \n";
    return 0;
}

void CenterOrigin(sf::Sprite & t)
{
    sf::FloatRect d = t.getLocalBounds();
    t.setOrigin(d.width / 2, d.height / 2);
}

每当我尝试构建这个项目时,都会收到大量的 LNK2005 错误,每个变量对应一个在 globals 头文件中声明的变量。我一直在寻找解决这个问题的方法,但是我找不到。我确保 globals.h 文件中没有定义,但是,我仍然无法构建项目。

如果我将所有定义移到 .h 文件中,这个问题就会自行解决,但是,通过 lnk2005 错误的 microsoft 页面,我发现这只是因为只有一个文件包含 globals 头文件。

旁注,有没有更好的方法来处理全局变量/函数?Extern 是一种选择,但是当你有很多全局变量时它变得太麻烦了。

标签: visual-c++sfml

解决方案


推荐阅读