multiple definition of class - c++

first of all I know that this question has been answered very often, but the answers didn't help me a lot...
That is the code which is causing the error.
#include "WayFinderClass.h"
WayFinderClass::WayFinderClass(int NavigationMapIndex) { ... };
int WayFinderClass::TotalNumberOfPoints(int point[100][100][2]) { ... };
int WayFinderClass::ConnectedWithXPoints(int point[100][100][2], int pointID) { ... };
void WayFinderClass::findWay(int start, int goal) { ... };
WayFinderClass.h :
#ifndef WAYFINDERCLASS_H_INCLUDED
#define WAYFINDERCLASS_H_INCLUDED
#include "NavigationMap.h"
class WayFinderClass {
public:
int finalWay[100];
int start;
int goal;
int alreadyCheckedInt[100];
void findWay(int start, int goal);
WayFinderClass(int NavigationMapIndex);
private:
int pointConnectedWith[100];
int wayProgress[100][100];
int numberOfPoints;
bool antsInProgress[100];
int TotalNumberOfPoints(int point[100][100][2]);
int ConnectedWithXPoints(int point[100][100][2], int pointID);
NewNavigationMap NavigationMap;
};
#endif // WAYFINDER_H_INCLUDED
And that is the error I get:
C:\{...} Line 3 multiple definition of 'WayFinderClass::WayFinderClass(int)'
So what am I supposed to do? I already tried to include the .h file but it didn't help me.
I also checked every other file whether the file WayFinderClass.cpp has been included a second time - but I found nothing.

You should not include source files (.cpp). Include headers instead.
Your problem was probably caused by including the source file in main.cpp as you said and then compiling it separately as well. In that case, functions defined in WayFinderClass.cpp would be defined again in main due to the inclusion and you can't have more than one definition for a function.

Related

can't use separate function files in eclipse

I am trying to declare the functions in separate files. In the code given below, my main() is defined in main.cpp and the int addition(int x, int y) is defined
in an another file named function.cpp.
My code:
main.cpp
#include "function.cpp"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 15;
int sum = addition(a,b);
cout<<"\nSum = "<<sum<<"\n";
return 0;
}
fucntion.cpp
int addition(int x, int y)
{
int sum = x + y;
return sum;
}
But by using the above cod in Eclipse i am getting the following error. On the other hand, if i compile the code manually using make
through the linux terminal then, the same got works.
ERROR:
/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: multiple definition of `addition(int, int)'
./funtion.o:/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: first defined here
collect2: ld returned 1 exit status.
First of all it is not recommended to include .cpp files. You should create header (.h) with declarations, put implementations to .cpp, like now and wherever you need to use it just include.h . You should also read about avoiding multiple includes by adding #ifndef/#define/#endif.
Update:
#include works in pre compiling phase and more or less it means "paste here what you have in file ...". So it copies function from one file and pastes to main file then compiles it. After this it compiles also cpp file with your function - also ok. Now comes linking: because of previous steps and copy-paste it has two definitions (actually two symbols) which has same name - that is causing the error and that's why we have headers :)
First create a header file, for example Addition.h and declare the function name inside it. Then make a file Addition.cpp and write the addition function implementation and then include the Addition.h in your main.cpp file.
The concept of using a header file is that you can use it anywhere else and is not limited to your main.cpp program file.
So, in short
Addition.h
class Addition { public:
int addition(int a , int b); //function declaration
private: int result_; };
then in Addition.cpp
#include Addition.h
int Addition::addition(int x, int y) {
// function implementation
}
in main.cpp
#include <Addition.h>
int main()
{ int a=3, b=4, sum=0;
Addition objAdd; //creation of object for class Addition
sum = objAdd.addition(a,b);
}
Hope this helps in structuring your code.

Static Functions in C++

I've read a few posts on here about static functions, but still am running into trouble with implementation.
I'm writing a hardcoded example of Dijkstra's algorithm for finding the shortest path.
Declared in Alg.h:
static void dijkstra();
Defined in Alg.cpp:
static void Alg::dijkstra() {
//Create Map
Initialize();
//Loop to pass through grid multiple times
for(int i=0; i<5; i++)
{
current=1;
while(current!=6)
{
//Iterate through and update distances/predecessors
//For loop to go through columns, while current iterates rows
for(int j=1; j<7; j++)
{
//Check if distance from current to this node is less than
//distance already stored in d[j] + weight of edge
if(distanceArray[current][j]+d[current]<d[j])
{
//Update distance
d[j] = distanceArray[current][j]+d[current];
//Update predecessor
p[j] = current;
}
}
//Go to next row in distanceArray[][]
current++;
} //End while
} //End for
output();
} //End Dijkstras
I want to call my function from main without an object. When I had all of this code in Main.cpp, it worked perfectly. Splitting it up into separate files caused the error Main.cpp:15: error: ‘dijkstra’ was not declared in this scope.The posts I came across when searching SE gave me me the impression that to do this, I needed to make that method static, yet I still have no luck.
What am I doing wrong?
Main.cpp:
#include <iostream>
#include "Alg.h"
int main() {
dijkstra();
return 0;
}
Edit: Added full header file, Alg.h:
#ifndef Alg_
#define Alg_
#include <iostream>
#include <stack>
using namespace std;
class Alg
{
public:
void tracePath(int x);
void output();
void printArray();
void Initialize();
static void dijkstra();
int current, mindex;
int distanceArray[7][7]; //2D array to hold the distances from each point to all others
int d[6]; //Single distance array from source to points
int p[6]; //Array to keep predecessors
int copyD[6]; //Copy of d[] used for sorting purposes in tracePath()
int order[6]; //Contains the order of the nodes path lengths in ascending order
}; //End alg class
#endif
Original all-in-one working Main.cpp file: http://pastebin.com/67u9hGsL
You should call it this way:
Alg::dijkstra();
Limitations
Can't call any other class functions that are not static.
Can't access non static class data members.
Can instantiate an object via new class() when constructor is private/protected. E.g. a factory function.
You can just use a namespace instead of having a class with all static members.
Alg.h:
namespace Alg
{
void dijkstra();
}
and in Alg.cpp
namespace Alg
{
void dijkstra()
{
// ... your code
}
}
in main.cpp
#include "Alg.h"
int argc, char **argv)
{
Alg::dijkstra();
return 1;
}
Are you sure the function is supposed to be static?
It looks as if you want just a function?
in your header file:
#ifndef DIJKSTRA_H
#define DIJKSTRA_H
void dijkstra();
#endif
in your cpp file
void dijkstra() {
/* do something */
}
in your main file:
#include "yourcppfile.h"
int main(int argc, char **argv) {
dijkstra();
}
if you really want a static function you have to put it into a nested class:
class Alg {
public:
static void dijkstra();
/* some other class related stuff */
}
the implementation somewhere in a cpp file
void Alg::dijkstra() {
/* your code here */
}
and then in your cpp file where the main resides
#include "your header file.h"
int main(int argc, char **argv) {
Alg::dijkstra();
}
If I remember right any 'static' function is limited to the module in which it is implemented. So, 'static' prevents using the function in another module.
In your header file Alg.h:
#ifndef __ALG_H__
#define __ALG_H__
namespace Alg {
void dijkstra();
}
#endif
The include guards are necessary if you plan to include the header in more than one of your cpp files. It seems you would like to put the function in a namespace Alg, right?
In Alg.cpp:
#include "Alg.h"
void Alg::dijkstra() { /* your implementation here */ }
Then, in main.cpp you call it with full namespace qualification:
#include "Alg.h"
int main() {
Alg::dijkstra();
}
If you just want to distribute your code over several files, I don't see why the function should be declared static.
You are confusing the 'static' keyword for local functions, with the 'static' keyword used in a class to make a function a class function and not an object function.
Remove static the first line of Alg.cpp and in the header file. This will allow Alg.o to contain global symbols that main can refer to and the linker can link.
You still need to call Alg::dijkstra() as was stated by #egur.
After this you may still get errors. The way you are using Alg:: is more like a namespace than a 'class' definition.
Now that we have the complete declaration of your class Arg, it feels like the singleton design pattern could be useful:
http://en.wikipedia.org/wiki/Singleton_pattern
The key here is the ‘dijkstra’ was not declared in this scope error.
Take your all-in-one source file and remove the main function. Make a new source file with this in it:
void dijkstra();
void output();
int main(int argc, char *argv[]) {
dijkstra();
output();
return 0;
}
The all-in-one cpp without a main plus this file above should compile together and give you the same result as before with one source, as it does for me. You will get a duplicate symbol _main error if you forgot to remove the main from the algorithm file.
No static needed.
My answer here fails to touch on good practices on header files, that is, you would want to include those function declarations in a .h file. It solves the compile-time error though.
You may want to find a good book to help you through some of the machinery of C++, where program context (in a linguistic sense) can change the meaning of keywords. This can be bewildering, and it proves to be exactly that for a language with as much colorful history as C++. Take a look here for book suggestions.

Include statement includes itself

I'm Working on a project in c++, but I am native to Java and have little c++ experience. the error i am having is that Cell and CellRenderer both include each other, but I have no idea how to fix this, as they both use one another. if I remove the #include, I get errors with cell, but if I keep it the errors disappear except for the Cell includes itself. This is my code:
#include <string>
#include <iostream>
#include <allegro5\allegro.h>
#include "Cell.h"
#include "Renderer.h"
using namespace std;
class CellRenderer: public Renderer{
Cell * cell;
ALLEGRO_BITMAP * image;
public:
CellRenderer(Cell * c)
{
cell = c;
image = cell->getImage();
}
void render(int x, int y)
{
al_draw_tinted_scaled_bitmap(image, cell->getColor(),0,0,al_get_bitmap_width(image),al_get_bitmap_height(image),x-cell->getRadius(),y-cell->getRadius(),cell->getRadius()*2,cell->getRadius()*2,0);
}
bool doesRender(int x, int y, int wid, int ht)
{
int cellX = cell->getX();
int cellY = cell->getY();
int radius = cell->getRadius();
return cellX>x-radius&&cellX<x+wid+radius&&cellY>y-radius&&cellY<y+ht+radius;
}
}
class Cell{
public:
bool doesRender(int x, int y, int wid, int ht)
{
return renderer->doesRender(x,y,wid,ht);
}
void render(int x, int y)//renders with center at x,y
{
renderer->render(x,y);
}
};
any help would be greatly appreciated
You need to surround all header file you write with guard.
There are 2 solutions to do that but only the 2nd will really works with all compilers.
Visual Studio supports #pragma once. Put that on the 1st line of your header.
All compiler have a preprocessor. Surround all the text in your header file with
#ifdef ...
#define ...
other include, class declaration, etc...
#endif
Replace the ... by a unique identifier for your file; for example, I often use as a convention:
_filenameinlowercase_h_
If you already have a header guard, please make sure that you didn't included the same header file in it by mistake.
Example
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
.
.
.
#include Example.h //It should be removed
.
.
#endif
Tip for the larger related issues. Sometimes the spelling might be off and it can be troubling to see where it is setup incorrectly if you have a large project with many include files.
I find compiling one file at a time can identify where the include was setup incorrectly.

Compiler Hiccup in C++ and with .o Files

I've been trying to compile a multi-file project, but every time I try to use a void in player.cpp, I keep getting this error message, which appears that the player.o that is created during compilation has the same definition of void player_action(...). When I tried to use a void in the other files, the same problem occurs, with their corresponding .o file. However, if I use structs in any of the files, no problems occurs, and no "multiple definition" error occurs. In the lines below is the error message the compiler is giving me.
obj\Debug\player.o: In function `Z13player_actioniii':
D:/Projects/Blackmail Mailman/player.cpp:13: multiple definition of `player_action(int, int, int)'
obj\Debug\main.o:D:/Projects/Blackmail Mailman/player.cpp:13: first defined here
This is the code from player.cpp I used:
#include "include_files.cpp"
struct player_struct
{
int x;
int y;
int previous_x;
int previous_y;
int mode;
};
void player_action(int x, int y, int mode)
{
SDL_Event event;
if (SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_RIGHT:;
};
};
};
};
What could be wrong and how can I fix it? I'm using Codeblocks with Mingw and Windows XP. I already checked the other files and there aren't any extra definitions of void player_action().
You never #include .cpp files, rather the .h files only.
If you need to access void player_action() from several parts of your program you should make a header file myapi.h which contains the following:
//myapi.h
#ifndef MYAPI_HEADER
#define MYAPI_HEADER
void player_action(int x, int y, int mode);
/* more function declarations */
#endif
The file which defines the function will be like this:
//player.cpp
#include "myapi.h"
void player_action(int x, int y, int mode)
{
/*...*/
}
and the file which uses it will be like this:
//main.cpp
#include "myapi.h"
void GameCycle()
{
/*...*/
player_action(0,0,0);
/*...*/
}
Never include objects definitions with #include, unless you know what you are doing. And even if you do know, you should think twice before doing so. Always use include guards (#ifndef ... #define .. #endif) - this will prevent multiple inclusion of your header.
These are the basic recommendations. I have seen a good explanation of such stuff in B. Stroustrup's 'The C++ programming language'

(C++) Linking with namespaces causes duplicate symbol error

For the past few days, I have been trying to figure out how to link the files for a CLI gaming project I have been working on. There are two halves of the project, the Client and the Server code.
The client needs two libraries I've made. The first is a general purpose game board. This is split between GameEngine.h and GameEngine.cpp. The header file looks something like this
namespace gfdGaming {
// struct sqr_size {
// Index x;
// Index y;
// };
typedef struct { Index x, y; } sqr_size;
const sqr_size sPos = {1, 1};
sqr_size sqr(Index x, Index y);
sqr_size ePos;
class board
{
// Prototypes / declarations for the class
}
}
And the CPP file is just giving everything content
#include "GameEngine.h"
type gfdGaming::board::functions
The client also has game-specific code (in this case, TicTacToe) split into declarations and definitions (TTT.h, Client.cpp). TTT.h is basically
#include "GameEngine.h"
#define TTTtar "localhost"
#define TTTport 2886
using namespace gfdGaming;
void* turnHandler(void*);
namespace nsTicTacToe
{
GFDCON gfd;
const char X = 'X';
const char O = 'O';
string MPhostname, mySID;
board TTTboard;
bool PlayerIsX = true, isMyTurn;
char Player = X, Player2 = O;
int recon(string* datHolder = NULL, bool force = false);
void initMP(bool create = false, string hn = TTTtar);
void init();
bool isTie();
int turnPlayer(Index loc, char lSym = Player);
bool checkWin(char sym = Player);
int mainloop();
int mainloopMP();
}; // NS
I made the decision to put this in a namespace to group it instead of a class because there are some parts that would not work well in OOP, and it's much easier to implement later on.
I have had trouble linking the client in the past, but this setup seems to work.
My server is also split into two files, Server.h and Server.cpp.
Server.h contains exactly:
#include "../TicTacToe/TTT.h" // Server needs a full copy of TicTacToe code
class TTTserv;
struct TTTachievement_requirement {
Index id;
Index loc;
bool inUse;
};
struct TTTachievement_t {
Index id;
bool achieved;
bool AND, inSameGame;
bool inUse;
bool (*lHandler)(TTTserv*);
char mustBeSym;
int mustBePlayer;
string name, description;
TTTachievement_requirement steps[safearray(8*8)];
};
class achievement_core_t : public GfdOogleTech {
public: // May be shifted to private
TTTachievement_t list[safearray(8*8)];
public:
achievement_core_t();
int insert(string name, string d, bool samegame, bool lAnd, int lSteps[8*8], int mbP=0, char mbS=0);
};
struct TTTplayer_t {
Index id;
bool inUse;
string ip, sessionID;
char sym;
int desc;
TTTachievement_t Ding[8*8];
};
struct TTTgame_t {
TTTplayer_t Player[safearray(2)];
TTTplayer_t Spectator;
achievement_core_t achievement_core;
Index cTurn, players;
port_t roomLoc;
bool inGame, Xused, Oused, newEvent;
};
class TTTserv : public gSserver {
TTTgame_t Game;
TTTplayer_t *cPlayer;
port_t conPort;
public:
achievement_core_t *achiev;
thread threads[8];
int parseit(string tDat, string tsIP);
Index conCount;
int parseit(string tDat, int tlUser, TTTplayer_t** retval);
private:
int parseProto(string dat, string sIP);
int parseProto(string dat, int lUser);
int cycleTurn();
void setup(port_t lPort = 0, bool complete = false);
public:
int newEvent;
TTTserv(port_t tlPort = TTTport, bool tcomplete = true);
TTTplayer_t* userDC(Index id, Index force = false);
int sendToPlayers(string dat, bool asMSG = false);
int mainLoop(volatile bool *play);
};
// Other
void* userHandler(void*);
void* handleUser(void*);
And in the CPP file I include Server.h and provide main() and the contents of all functions previously declared.
Now to the problem at hand
I am having issues when linking my server. More specifically, I get a duplicate symbol error for every variable in nsTicTacToe (and possibly in gfdGaming as well). Since I need the TicTacToe functions, I link Client.cpp ( without main() ) when building the server
ld: duplicate symbol nsTicTacToe::PlayerIsX in Client.o and Server.o
collect2: ld returned 1 exit status
Command /Developer/usr/bin/g++-4.2 failed with exit code 1
It stops once a problem is encountered, but if PlayerIsX is removed / changed temporarily than another variable causes an error
Essentially, I am looking for any advice on how to better organize my code to hopefully fix these errors.
Disclaimers:
-I apologize in advance if I provided too much or too little information, as it is my first time posting
-I have tried using static and extern to fix these problems, but apparently those are not what I need
Thank you to anyone who takes the time to read all of this and respond =)
You get error about duplicate definitions because that's what you have: each time a .cpp file includes TTT.h, a global bool PlayerIsX is defined (in the nsTicTacToe namespace, but still global). In this case, it's Server.cpp and Client.cpp that are including it.
One way to solve this could be to change the definitions into declarations by using extern, then doing the actual definition in a corresponding .cpp file (TTT.cpp, for instance).
In TTT.h:
namespace nsTicTacToe {
...
extern bool PlayerIsX;
...
}
In TTT.cpp:
#include "TTT.h"
bool nsTicTacToe::PlayerIsX;
and so on for the other definitions.
By the way, remember to have proper guard #ifdefs:
#ifndef __TTT_H
#define __TTT_H
... header contents
#endif // __TTT_H
Actually, extern IS what you need. You're probably just not realizing or remembering that you'll also have to define such variables in a cpp file.
header:
extern int somevar;
source:
int somevar = ?;
By putting all of your globals in the header you're making copies of them everywhere you include them, which is exactly what your compiler is bitching about.
You are essentially using globals, which is strongly not recommended in C++, but is sometimes necessary in C.
You could get it working with extern, but the "better" answer would be to wrap your globals in a state object of some sort.
struct State
{
GFDCON gfd;
const char X;
const char O;
string MPhostname, mySID;
board TTTboard;
bool PlayerIsX, isMyTurn;
char Player, Player2;
};
Create your state object in Main and pass it to each function that needs to know the state of the game system.
This will lead to much better code organization in the long run.
you could put the namespace nsTicTacToe part into it's own .cpp file, compile it separately and link it in.
You might also need a header file which just declares externs for the variables, and include that in you client and server .cpp files.