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.
Related
This question already has answers here:
Separating class code into a header and cpp file
(8 answers)
Closed 5 years ago.
I have that common LNK2019 error and can not figure out what is wrong.
Here is my Solution Explorer:
Here is my Rectangle.cpp:
class Rectangle
{
public:
int getArea()
{
return this->width*this->height;
}
int width;
int height;
};
Here is my Rectangle.h:
#pragma once
class Rectangle
{
public:
int getArea();
int width;
int height;
};
Here is my Functions.cpp:
#include <iostream>
#include "Rectangle.h";
using namespace std;
int main()
{
Rectangle r3{ 2, 3 };
cout << r3.getArea();
return 0;
}
I am very new to C++ and it seems I did everything correctly, but still I am getting an error.
Rectangle.cpp should be like this:
#include "Rectangle.h"
int Rectangle::getArea() {
return this->width*this->height;
}
You shouldn't redefine the class definition in the source file, since you already have it in the header file!
When you want to write the body of a class function, you need to write it this way :
#include "Rectangle.h"
int Rectangle::getArea()
{
return this->width*this->height;
}
You do not need to redefine your class into the cpp file.
You define everything inside the header (.h, .hpp), you include it inside the cpp file (#include "Rectangle.h") but you must not redeclare everything in the header file.
By the way, since you are writing a method, you can access member variables directly by width and you do not need to use this->width.
However, I recommand you to use a convention when you are writing your own classes.
My convention is to prefix member variable by a m. (In your case it gives you mWidth or mHeight).
There is other people that have other conventions like m_variable or variable_.
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.
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.
i'm having the fallowing header file. I get this error: expected ')' before 'A' why is this?
I tried to rewrite and to replace... i`m out of ideas and i dont know what may be the root of the problem...
#ifndef UICONSOLE_H_
#define UICONSOLE_H_
#include "Catalog.h"
#include <string>
using namespace std;
class UIconsole{
public:
UIconsole(Catalog A); // error here.
void runUI();
private:
void showMenu();
string getString();
int getOption();
void addStudent();
void removeStudent();
void editStudent();
void printStudent();
void printAllStudents();
void addAssignment();
void removeAssignment();
void editAssignment();
void printAssignment();
void printAllAssignment();
void printAllUnder5();
void sortAlphabetically();
void searchById();
};
#endif /* UICONSOLE_H_ */
edit, with the content of a dependency header:
#ifndef CATALOG_H_
#define CATALOG_H_
#include <string>
#include "UIconsole.h"
#include "Catalog.h"
#include "StudentRepository.h"
#include "StudentValidator.h"
using namespace std;
class Catalog{
private:
StudentRepository studRepo;
StudentValidator studValid;
public:
Catalog(StudentRepository stre, StudentValidator stva):studRepo(stre),studValid(stva){};
void addNewStudent(string name, int id, int group);
void removeStudent(string name);
void editStudent(int name, int id, int group);
Student seachStudent(string name);
};
#endif /* CATALOG_H_ */
Your Catalog.h file has a couple of unnecessary #include directives:
#include "UIconsole.h"
#include "Catalog.h"
Get rid of these from the particular file.
The #include "Catalog.h" is unnecessary, but harmless (because of the include guards). However, the #include "UIconsole.h" causes the declaration of class UIconsole to be processed before the declaration of class Catalog. So when the compiler hits the
UIconsole(Catalog A);
line it still has no idea what Catalog is.
Another thing that's unrelated to this problem but should be fixed is the
using namespace std;
directives in the header files. That's a bad practice that should be avoided - in header files you should generally specify the full name of types in the std namespace:
void addNewStudent(std::string name, int id, int group);
void removeStudent(std::string name);
Forcing a namespace into the global namespace on all users of a header can cause problems when there's a name conflict (essentially, you're removing the ability for users to control name conflicts with namespaces if you force the directive on them).
You have a circular include: Catalog includes Console, which in turn includes catalog again. Now the safeguard prevent the infinite include, but it does not magically solve the problem.
Lets assume that in your case, Catalog is included first:
The compiler does:
include Catalog. h
include Console.h
Include Catalog.h but actually skip the content because of the safeguard.
continue with processing Console.h but it has not seen the Catalog class yet.
You need to solve the circular include. One way would be to put a pointer instead of an object Catalog and have a forward declaration. Or you can simply remove the include UIconsole.h from Catalog.h, as it does not seem to be needed in the header.
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'