-
Multi link errors
I am starting a large application involving classes and different files.
I have created a player class and set it as a header file so i can use it in my other files without having to "extern" call all the variables,
The class name and the object player have both been defined in the main() function in the first cpp file.
But when i went to create my next cpp file, I included my file that has the player class like this:
[code]#include "player.h"[\code]
and when i went to compile i got 15 linker errors up saying stuff like:
error: 'int health' multiple definiotion - first defined here
I though that if i placed my class in a header file then i could just include it with my other files... what am i doing wrong?
-
the the top of your header file include
#ifndef MYHEADER_H
#define MYHEADER_H
then at the end add
#endif /* MYHEADER_H */
(and change MYHEADER_H to something more relevent to file)
-
Here is my header file for my Player Class
Code:
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
using std::string;
class Player
{
public:
int hp;
int score;
int level;
Player ( int h, int s, int l );
private:
bool palive;
bool pdead;
};
Player::Player ( int h, int s, int l )
{
hp = h;
score = s;
level = l;
palive = true;
pdead = false;
}
#endif
Error I get when including it in my new cpp file:
multiple definition of `Player::Player(int, int, int)'
first defined here 'LINKER ERROR MSVC++2003
It works fine included in the file with main()
-
Code:
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
using std::string;
class Player
{
public:
int hp;
int score;
int level;
Player ( int h, int s, int l );
private:
bool palive;
bool pdead;
};
//!! Move this function to player.cpp, and #include player.h in that file as well
//!! You're getting a copy of this function in all your .cpp files, so it becomes multiply declared.
Player::Player ( int h, int s, int l )
{
hp = h;
score = s;
level = l;
palive = true;
pdead = false;
}
#endif
-
The only functions you should put into header files are inline functions, which have to be declared in every file they're used in.