Undefined reference to class constructor, including .cpp file fixes - c++

The problem I am having is that, when I call a constructor for a class I have created I get the following error.
main.cpp:20: undefined reference to
`StaticObject::StaticObject(Graphics*, sf::String,
sf::Vector2)'
This problem can be 'fixed' adding an include for the .cpp file in main.cpp like so.
...
#include "GameObjects/StaticObject.cpp"
...
Although this solves the problem, this seems like a poor solution and goes against what I have been previously told. Is there any other way to solve this problem? I'm using Netbeans 7.3 with g++ to code/compile this program. Below is the relevant code.
main.cpp
...
#include <SFML/Graphics.hpp>
#include "Graphics/Graphics.hpp"
#include "GameObjects/StaticObject.hpp"
int main(int argc, char** argv) {
//SETUP
Graphics graphics;
background = new StaticObject(&graphics, "Data/Images/BackgroundPlaceholder.png", sf::Vector2f(0,0));
...
main.hpp
...
#include <SFML/Graphics.hpp>
#include "GameObjects/StaticObject.hpp"
...
// Objects
StaticObject *background;
...
StaticObject.hpp
#include <SFML/Graphics.hpp>
#include "../Graphics/Graphics.hpp"
class StaticObject{
public:
StaticObject();
StaticObject(Graphics *_graphics, sf::String texture_filename, sf::Vector2f _position);
StaticObject(const StaticObject& orig);
virtual ~StaticObject();
private:
// The sprite stores the position
sf::Sprite *sprite;
sf::Texture *texture;
};
StaticObject.cpp
#include "StaticObject.hpp"
#include <SFML/Graphics.hpp>
#include "../Graphics/Graphics.hpp"
StaticObject::StaticObject(){
}
StaticObject::StaticObject(Graphics *_graphics, sf::String texture_filename, sf::Vector2f _position) {
sprite = _graphics->AddSprite(texture_filename);
sprite->setPosition(_position);
}
StaticObject::StaticObject(const StaticObject& orig) {
}
StaticObject::~StaticObject() {
}
If I add the following line to main.cpp, the error disappears.
#include "GameObject/StaticObject.cpp"
Can anyone please explain:
Why this fixes the problem?
Why the .cpp was not implicitly included through including the .hpp
file?
Is there a better way of doing this?

The undefined reference error indicates that the definition of a function/method (i.e constructor here) was not found by the linker.
StaticObject::StaticObject(Graphics*, sf::String, sf::Vector2<float>)
And the reason that adding the following line:
#include "GameObject/StaticObject.cpp"
fixes the issue, is it brings in the implementation as part of the main.cpp whereas your actual implementation is in StaticObject.cpp. This is an incorrect way to fix this problem.
I haven't used Netbeans much, but there should be an option to add all the .cpp files into a single project, so that Netbeans takes care of linking all the .o files into a single executable.
If StaticObject.cpp is built into a library of its own (I highly doubt that is the case here), then you might have to specify the path to the location of this library, so that the linker can find the implementation.
This is what ideally happens when you build your program:
Compile: StaticObject.cpp -> StaticObject.o
Compile: main.cpp -> main.o
Link: StaticObject.o, main.o -> main_program
Although there are ways in gcc/g++ to skip all the intermediate .o file generations and directly generate the main_program, if you specify all the source files (and any libraries) in the same command line.

The linker cannot find the definition for StaticObject, which means you have not compiled and linked StaticObject.cpp. Each .cpp file needs to be separately compiled, and the object files the compiler produces for each one needs to be given to the linker.
The reason including StaticObject.cpp in Main.cpp works is that you are telling the preprocessor to insert the contents of StaticObject.cpp into Main.cpp, which you are compiling, so the definitions become part of Main.cpp's compiled output.

including the cpp file causes the compiler to build that code as part of that file (which you should not do), what you need to do is compile the GameObject/StaticObject.cpp file as its own object, and link the 2 objects together.

I dont know much of netbeans, but probably GameObject/StaticObject.cpp is not included as part of the sources to compile.
That's why if you include it manually at main.cpp he found source code and everything is ok.

I had the same issue but mine was because I'm using Eclipse CDT with and Autotools project. So I had to manually add the new .h and .cpp files to the corresponding Makefile.am, and then do a project > reconfigure project, rebuild, an that was it.

I had the same issue in Qt, where I forgot to add the class to the pro file. Apparently, without adding it to the pro file, the compiler doesn't recognize it. So I added it in, and then ran qmake again, and that silved the problem.
Basically, you need to add the file in the sources.

Related

How does C++ linker know what .cpp files to use

I am a C++ learner and I came across a concept of separating code into multiple files to speed up compiling process on bigger projects.
However what the book doesn't tell me and I have tried to find it in other books and on the web, but with no luck is how does linker (during compilation) knows what files to include.
When I make new file I connect its header to the main file with #include "newfile.h", however in this header I don't write where to find definitions of functions.
So how I imagine the process is that it starts in the main file and there it finds "connections" to other files. The question is how it finds those .cpp files that as far as I see don't need to be named the same as its header file.
Exmple:
Main file:
#include <iostream>
#include "krneki_H.h"
using namespace std;
int main()
{
krneki1();
krneki2();
krneki3();
}
And header file:
void krneki1();
void krneki2();
void krneki3();
And new .cpp file:
#include <iostream>
#include "krneki_H.h"
using namespace std;
void krneki1() {
cout<<"Krneki1"<<endl;}
void krneki2() {
cout<<"Krneki2"<<endl;}
void krneki3() {
cout<<"Krneki3"<<endl;}
Notice that there is no indication to use second cpp file. It just knows to use it. Does it search all .cpp files in the map?
Thank you for answer.
You compile both .cpp files using gcc -c or a similar command line, and then pass both of the .o files produced to the linker. The linker does not magically figure out that you want to compile another .cpp file.
For example
gcc -c main.cpp -o main.o # compile
gcc -c krneki_H.cpp -o krneki_H.o # compile
gcc main.o krneki_H.o -o main # link
Your IDE may take care of these details automatically, in which case it compiles all .cpp files you added to your project, then links all the .o files produced by the compilation step.
No. It doesn't just know to use it. In your example, if you compile with main.cpp and without that new cpp file, you'll get an "undefined reference" error.
What happens is that you're using a fancy IDE that automatically compiles all cpp files. It includes them all by default in your makefile.
I recommend that you try to design a makefile from scratch, and see for yourself how you'll get that "undefined reference" error if you don't include the cpp file that has the implementations of your functions.

Object files with visual studio

I have a main file main.cpp which include myclass.h. I also have myclass.o and myclass.cpp. The visual studio project is only using the files main.cpp and myclass.h.
This compile:
#include "myclass.h"
int main()
{
return 0;
}
This does not:
#include "myclass.h"
int main()
{
myclass M{};
return 0;
}
which gives a link error - probably because the myclass.cpp or myclass.o is not included in the project.
I would prefer to include only myclass.o since compiling this class is very problematic.
See
https://forum.qt.io/topic/8492/solved-cannot-get-quazip-test-to-work/3
if you are curious of which library I am using.
To my question:
Can I compile and use the class with only the header and the object file, i.e without the .cpp file at all?
Thanks!
Visual Studio generates a .obj file as its intermediate format. gcc and gcc are the ones that produce a .o file. You can include this in your project or, since libraries rarely have a single compile unit, you can build a .lib file and include that. Be warned, though, that the compiled units must be compiled using the exact same compiler switches such as run time library and etc. as you are using in you project. It is often simpler to simply compile the file from source.
We can also talk about using a DLL but that seems to be beyond the scope of your question and also introduces the complication of calling conventions.

Code::Blocks is not making object files

First of all, I am a beginner programmer so, please give simple answers that are understandable.
I am suing Code::Blocks and I am trying to make a multiple file project in C++. I am using SDL2. My problem is that when I put all my codes and functions altogether, they run and when I seperate them, they don't. This is because the execution file requires object files to be built which it don't get. It don't get them because compiler don't form them. In other words, there are problems with linking. The compiler simply, said that there are not ".o" files. These files are in the project as "Link Files" and not "Compile Files". And when I make them "Compile Files" as well as "Link Files", they produces errors that various variables inside the file where I mentioned them, are not declared. But when I include that file in the file using the variables, it gets deeply nested.
Following are the two ways:
First way which is not working, with seperate files.
In main.cpp:
#include <SDL.h>
#include <other.h>
int var;
int linkVar;
int link1Var;
int link2Var;
#include "link.cpp"
#include "link1.cpp"
#include "link2.cpp"
int main( int argc, char* args[] )
{
linkFunc();
link1Func();
link2Func();
}
In link.cpp/ link1.cpp/ link2.cpp:
void linkFunc()/void link1Func()/void link2Func() //Just a reference
{
//Code associated with var, link1Var, link2Var and link3Var.
}
Second way which is working, with all functions in a single file.
First thing is that I don't want to learn makefile thing. If there is any other way to solve it then be it!
Code::Blocks makes object files for each file that it compiles as separate compilation units. It will compile and link together any files that are part of the project which it identifies as a source file.
First, remove your #includes of the cpp files. Then try the Project > Add files... menu option to add those other cpp files to the project.
First of all, you should not use #include on other cpp files, you can read about it here:
include cpp
Secondly when you are trying to compile a project composed of separate files you should use the g++ command like this: g++ main.cpp link.cpp link2.cpp etc'
you can read a basic explanation about it here: use the g++ command
To do exactly what you asked you should do:
# get rid of including any cpp files
# use forward declerations on any function belonging in other cpp files, before your main function like this:
void linkfunc();
void linkfunc2();
etc
.
.
.
int main()
{
}
# specify the direct path to your .h files like this:
#include <C:/MinGW/SDL2/SDL.h>
# use this command:
g++ -I C:/MinGW/SDL2/ main.cpp link.cpp link2.cpp link3.cpp

Why does Visual Studio error when linking having files included?

I don't really understand the why behind this, but I think I've figured out the what.
My brother is working on a homework project and they're using Visual Studio. He was having issues getting his project to compile. The project in question consisted of:
main.cpp
classes.h
class_functions.cpp
general_functions.cpp
They had the following import structure:
main.cpp
#include "classes.h"
#include "class_functions.cpp"
#include "general_functions.cpp"
class_functions.cpp
#include "classes.h"
general_functions.cpp
#include "classes.h"
He kept getting link errors when trying to compile, even though g++ would compile it just fine. So I tried via Visual Studio command prompt and cl. This compiled just fine, so I tried msbuild which (obviously?) failed. I went into the vxproj file, because hey, what is it telling cl that I'm not?
In the proj file it was including classes.h, general_functions.cpp and class_functions.cpp, as well as main.cpp. When I removed general and class functions, msbuild ran just fine. Put either of them back and boom. classes.h contains
#ifndef myclasses
#define myclasses
/* Code here */
#endif
And the other .cpp files contain similar directives.
I finally figured out how to eliminate the problem - eliminate
#include "general_functions.cpp"
#include "class_functions.cpp"
from the code base, and now Visual Studio compiles this just fine.
The question is why? What is the justification or possible benefits from doing this?
the difference between .cpp and .h files is that the .h files are usually included with the #include directive while .cpp files are included in the linking process.
The #include instruction will insert a copy of the included file in the code you are compiling, so by including the .cpp files you will compile a single source file that contains all your .cpp files. It's very bad practice but still could work.
But if you are then adding the .cpp files also in the linking step then you are adding those files a second time creating probably duplicate definitions of your functions, e.g. linker error. I think that's probably the main error (without the linker error codes I'm just guessing).

Creating class in separate file (beginner)

I am really new to C++, and I am trying to create a class in a separate file, and I ran into a problem. I basically copied the tutorial http://thenewboston.org/watch.php?cat=16&number=15 from the newboston word for word. However, for the things don't work. I am getting this error when I am trying to run the main file:
C:\Users\Akavall\Desktop\C++ Stuff\New C++ stuff\class_try.o:class_try.cpp|| undefined reference to `Burrito::Burrito()'|
||=== Build finished: 1 errors, 0 warnings ===|
Also, when I am creating the class. The Workspace icon is sitting by itself, while it is supposed to (I believe) include my .cpp and .h folders of the just created class.
My guess is that my paths are not set correctly somewhere, but I have no idea how to fix that. Any suggestions?
Here is the code that I am using:
Main file (class_try.cpp)
#include <iostream>
#include "Burrito.h"
using namespace std;
int main()
{
Burrito bo;
return 0;
}
The class files:
Burrito.h
#ifndef BURRITO_H
#define BURRITO_H
class Burrito
{
public:
Burrito();
};
#endif // BURRITO_H
Burrito.cpp
#include "Burrito.h"
#include <iostream>
using namespace std;
Burrito::Burrito()
{
cout<<"something silly"<<endl;
}
What should I do to fix the this problem?
Thank You in Advance
Edit:
I am using CodeBlocks, and I am on 32bit windows.
If you are using MSVC like that tutorial you linked, you need to first create a project. After creating the project, add all the header (.h) and source (.cpp/.cxx) files that you want to include/compile in it. Now, MSVC makes this easy from this point; you can simply compile (as long as everything is properly added to your project) and it will compile things in order for you.
Extra Information
The information below is not directly pertinent to this issue (or at least doesn't seem that way since you're on Windows), but is intended to help your growth as a developer if you want it.
If, however, you ever decide to use a command line compiler (i.e. MingW) or work in a *nix environment, it is important to note that you need to explicitly compile each object (without linking; in gcc/mingw this flag is -c). Then at the end of compiling several unlinked object, you compile all the objects and the main source file together (with linking this time) and it will create one executable.
I would recommend, however, before trying a command line compiler that you get comfortable/familiar with doing this process through an IDE. Since it is generally an automated process anyway (i.e. most developers end up writing Makefile's for this kind of thing, realistically) you do not really lose too much (immediately, anyway) by not doing this. It is just something to be aware of as you learn.
Using command line compiler you can try this:
g++ class_try.cpp Burrito.cpp -o executable_name
This will link your two .cpp files and create an executable file and you can run that executable file just by typing
./executable_name