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
I’m getting the latter when trying to declare a function in the header.
I’m not sure what’s causing this, everything has include guards.
Funny thing is: if I define the function in the header as inline, it compiles.
Can anyone help?
See code Below:
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);
}
You can not define functions in headers like that. Either mark it as
staticorinlineor it will be defined in all source files where you include the header.If you want to use the function from several source files, only declare it in the header:
(Note the semicolon and no function body.)
Then define the function in one of your source files.