c++ - LNK2005 - 在 .hpp 文件中声明函数时出错

标签 c++ function sfml lnk2005

<分区>

我正在构建一个程序,需要一个函数来检查鼠标是否在某个对象上。我编写了该函数并创建了一个新的 .hpp-File,因为我项目中的多个文件将使用该函数。该文件名为 HitboxDetec.hpp。我在里面写的函数是这样的:

bool isClicked(sf::Sprite* Sprite, sf::RenderWindow* pW)
{
    int MOUSE_X = sf::Mouse::getPosition(*pW).x;
    int MOUSE_Y = sf::Mouse::getPosition(*pW).y;

    if (MOUSE_X >= Sprite->getPosition().x &&
        MOUSE_X <= Sprite->getPosition().x + Sprite->getPosition().x + 500 &&
        MOUSE_Y >= Sprite->getPosition().y &&
        MOUSE_Y <= Sprite->getPosition().y + Sprite->getPosition().y + 500)
    {
        return true;
    }
    else return false;
}

我包含了所需的库等,并且代码有效(我通过在我的 .cpp 文件中声明函数来测试它)。

在我的 .cpp 文件中,我包含了 CookieDetec.hpp-文件,并用

调用它
if(isClicked(pSprite, pW)) {Stuff}

当我编译我的程序时,它只给我一个 LNK2005-Error。我该如何解决这个问题?

最佳答案

LNK2005 用于:

The given symbol, displayed in its decorated form, was multiply defined.

如果您在头文件中定义函数,那么它可能包含在多个翻译单元中。为防止多次定义,将此函数标记为内联:

inline bool isClicked(sf::Sprite* Sprite, sf::RenderWindow* pW)
^^^^^^

关于c++ - LNK2005 - 在 .hpp 文件中声明函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37188739/

相关文章:

bash - 如何从函数中有效地中止 Bash 脚本的执行

java - 使用函数输入 Hibernate 参数

c++ - 为什么 g++ 不使用 -I 选项?

c++ - 未定义的 impl 引用

c++ - 在模板参数包上使用类型特征?

c++ - 如何将 float 转换为 int 保留位值

R 编程 : Is it possible to declare return or parameter types of functions?

c++ - 这个右移是如何工作的 : stringstream >> unsigned int >> unsigned int?

c++ - vector::引用

c++ - 为什么我没有得到匹配的调用函数