Compiler Hiccup in C++ and with .o Files - c++

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'

Related

How do you define a "Hello World" function in a seperate file in c++

and I apologize for asking a very basic question, but basically, I'm not able to wrap my head around include "fileImade.h"
I'm trying to write a main function, that's something like
int main()
{
int x = 5;
int y x 6;
std::cout << add(x, y) << std::endl;
}
where add() is defined in a separate .cpp file, and #include -ed in this one, (I'm doing this because I'm getting the point where my code is getting impractically large to do in a single file.), but my understanding is that you need a header file to... Glue your other files together, or I guess mortar them if the files are the bricks, but I absolutely cannot figure out how to make this work for the life of me.
(while using g++), should I tag -I? According to me googling, yes, according to my compiler output, no.
Should I write a header file and a .cpp files for the add() function? Apparantly, yes, or no, if I choose to write both files in the command line before the -o.
Should I include a forward declaration of the function in my main.cpp file? Again, according to the internet, yes, though that's not working terribly well for me.
So to my question: Can someone show me a main() function that calls a hello world() function in a separate file?
I'm honestly at my wits' end with this because all the guides seem to be on defining classes in header files, which, while useful, is a bit beyond the scope of what I'm attempting right now.
Thank you in advance for reading, and any advice offered.
The logic of the file separation may be imagined as:
(single file program)
/// DECLARATION of all functions needed in the main
int add(int x, int y); // declaration of add
///
int main()
{
std::cout << add(2, 3) << std::endl;
return 0;
}
/// IMPLEMENTATION of all functions needed in the main
int add(int x, int y)
{
return x + y;
}
The next you have to do is move all declarations to the headers and implementations to the cpps:
(separated files program)
/// add.h
#ifndef ADD_H /// https://en.wikipedia.org/wiki/Include_guard
#define ADD_H
int add(int x, int y);
#endif
/// main.cpp
#include "add.h"
int main()
{
std::cout << add(2, 3) << std::endl;
return 0;
}
/// add.cpp
#include "add.h"
int add(int x, int y)
{
return x + y;
}

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.

multiple definition of class

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.

C++ Class Files

I am having much trouble learning to use files for classes in C++. To learn I use Bucky Roberts/The New Boston C++ tutorials, I have tried exactly what he does, but it does not work.
I have the main.cpp and the OtherClass.cpp with the OtherClass.h for header. Every time I try doing OtherClass::OtherClass(){} for the constructor it errors out with "C++ requires a type specifier for all declarations"
Could someone give me an example of how to do C++ class files correctly? Really confused right now.
Thanks!
A simple example of using header files for classes (with the implementation in a separate .cpp file) looks something like this:
Your main.cpp file:
#include "OtherClass.h"
int main()
{
OtherClass otherClass;
//use otherClass here...
}
Next, your OtherClass.h file:
class OtherClass
{
public:
OtherClass();
int someFunction(int parameters);
};
And then finally your OtherClass.cpp file:
#include "OtherClass.h"
OtherClass::OtherClass()
{
//implementation here
}
int OtherClass::someFunction(int parameters)
{
//implemenation here
return 0;
}
The main things to keep in mind:
#include "OtherClass.h" goes in both OtherClass.cpp and main.cpp
make sure you finish constructor and function declarations with ';' not '{}' if you are defining the implementation elsewhere.
make sure you're compiling OtherClass.cpp as well as main.cpp. With MinGW this looks like g++ main.cpp OtherClass.cpp
Your question is a little cryptic to understand, but if I understand correctly you're looking for the `correct' way to create classes with interfaces in the header file. Here is an example of a class that does this:
Scene.h
#pragma once
#include "Window.h"
#include "Entity.h"
class Scene
{
public:
Scene(Window *_window);
~Scene(void);
void render(Entity item);
void render(Entity item, SDL_Rect *clip);
protected:
Window *window;
};
Scene.cpp
#include "Scene.h"
Scene::Scene(Window *_window)
{
window = _window;
}
Scene::~Scene(void)
{
}
void Scene::render(Entity item) {
render(item, NULL);
}
void Scene::render(Entity item, SDL_Rect *clip) {
window->draw( item.getImage(), item.getCoordinates(), clip, item.getAngle() );
}
Notice that the header file includes the headers that it needs to link properly, while the implementation file (.cpp) just includes the header file. The linker should automatically manage all this trouble for you as long as you stick to these semantics.
I hope this helps; if it doesn't, consider rephrasing your question or pasting some code.

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.