错误:(functionName)已经在Algorithms.obj中定义

Error: (functionName) already defined in Algorithms.obj

本文关键字:Algorithms obj 定义 functionName 错误      更新时间:2023-10-16
1>GameWinMain.obj : error LNK2005: "bool __cdecl BPredicate(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?BPredicate@@YA_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0@Z) already defined in Algorithms.obj
1>C:Algorithms.exe : fatal error LNK1169: one or more multiply defined symbols found

当试图在头文件中声明函数时,我得到了后者。我不确定是什么原因造成的,所有东西都有警卫。有趣的是:如果我在头文件中将函数定义为内联,它就会编译。有人能帮忙吗?

见下面代码:

Algorithms.h

#pragma once
//...other code
bool BPredicate(const string& a, const string& b){
    string::const_iterator it;
    UINT numA = 0;
    UINT numB = 0;
    for (it = a.begin(); it != a.end(); ++it) {
        if((*it) == ' ') {
            if (*(it-1) != ' ') {
                ++numA;
            }
        }
    }
    for (it = b.begin(); it != b.end(); ++it) {
        if((*it) == ' ') {
            if (*(it-1) != ' ') {
                ++numB;
            }
        }
    }
    return (numA < numB);
}

GameWinMain.h

#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow);

GameWinMain.cpp

#include "GameWinMain.h"
#include "GameEngine.h"
#include "Algorithms.h" 
#define GAME_ENGINE (GameEngine::GetSingleton())
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
    if (GAME_ENGINE == NULL) return FALSE; 
    GAME_ENGINE->SetGame(new Algorithms()); 
    return GAME_ENGINE->Run(hInstance, iCmdShow); 
}

你不能在头文件中这样定义函数。将其标记为staticinline,否则它将在包含头文件的所有源文件中定义。

如果您想使用来自多个源文件的函数,只需在头文件中声明:

bool BPredicate(const string& a, const string& b);

(注意分号,没有函数体)

然后在一个源文件中定义函数