I'm a Java developer experimenting with C++.
I just created a new class. In my other class I want to have list where I can store Filter objects.
Filter.h
#ifndef FILTER_H_
#define FILTER_H_
class Filter {
public:
Filter(int id);
int id;
~Filter();
};
#endif /* FILTER_H_ */
Filter.cpp
#include "Filter.h"
Filter::Filter(int id) {
this.id = id;
}
Filter::~Filter() {
}
Cars.h
#include "Filter.h"
...
...
private:
std::vector<Filter> filters;
Cars.cpp
so in a function here I try to do this:
int id = 2;
Filter *filter = new Filter(id);
which generate this error:
Cars.cpp:120: undefined reference to `Filter::Filter(int)'
stl_construct.h:83: undefined reference to `Filter::~Filter()'
What's the reason for this?
The error is generated by the linker because it can not see where the definition of the constructor is located.
If you are using an IDE, you should add both .cpp files to the project so that they can be compiled together and the definition would be found by the linker.
If not, then you have to combine them yourself -assuming you are using gcc:
g++ cars.cpp filter.cpp
will combine them into one executable and should not show you that error
Related
I am working on a circuit simulator/pathfinding system, but I keep getting these weird compilation errors. I am not yet that experienced with OO C++ to figure it out myself...
Object Tree
The objects in my project are implemented in this way:
Object
Component
Wire
Switch
Ciruit
My Object class is the base class for everything in my project, this is great for debugging by giving everything a name and an id.
I required that every component needs a Circuit to with (see it as a parent for components). I implemented this by creating a constructor in the Component class that requires a reference to a Circuit object.
At first, everything worked and compiled fine, but when I introduced the Circuit class and when I added a constructor in Component with a Circuit reference parameter, everything went wrong...
Compilation errors
Now I keep getting these seemingly random syntax and missing tokens errors. (Intellisense does not mark them?)
The first four errors that pop up are:
C2238: unexpected token(s) preceding ';'.
At line 10 of Component.hpp. And at line 12 in file Circuit.hpp.
Both just after the constructor definition. (See in code below)
The next four errors point tot the same locations, but it notes:
C2143: syntax error: missing ';' before '*'.
Then, 30 more errors follow, but I think they are a result of these errors, to be sure, here they are:
(Lol, cannot embed image, caused by not having enough reputation, so a link instead...)
Click here for errors
What I tried
I tried the following:
Using a reference instead of pointer. (changed Circuit* c to Circuit& c)
Removing the name string concationation thing in constructor initializer list. (changed ... : Object(name + "blah") to ... : Object(name))
Rewriting the whole Visual Studio project to a new Visual Studio project.
Placing the constructor initializer list in the header file.
Lots of googling... and not lots of solving...
How to fix?
This frustrating problem is stopping me from working further on this project, what is causing it and how do I fix it? I would be pretty happy to know.
Object.hpp
#pragma once
#include <string>
using std::string;
class Object
{
public:
Object();
Object(string name);
string name;
const int id;
virtual string toString();
private:
static int currentId;
};
Object.cpp
#include "Object.hpp"
int Object::currentId = 0;
Object::Object() : id(++Object::currentId), name("Object")
{ }
Object::Object(string name) : id(++Object::currentId), name(name)
{ }
string Object::toString()
{
return name + "#" + std::to_string(id);
}
Component.hpp
#pragma once
#include "Object.hpp"
#include "Circuit.hpp"
class Component : public Object
{
public:
Component(std::string name, Circuit* container);
Circuit *container; // <- Error points to the beginning of this line
};
Component.cpp
#include "Component.hpp"
Component::Component(string name, Circuit* container) : Object(name), container(container)
{ }
Switch.hpp
#pragma once
#include "Component.hpp"
#include "Wire.hpp"
class Switch : public Component
{
public:
Switch(string name, Circuit* container, Wire& wire1, Wire& wire2);
Wire* wire1;
Wire* wire2;
void setEnabled(bool enabled);
bool getEnabled();
private:
bool enabled;
};
Switch.cpp
Switch::Switch(string name, Circuit* container, Wire& wire1, Wire& wire2) : Component(name + "-Switch", container), wire1(&wire1), wire2(&wire2), enabled(false)
{ }
...
Circuit.hpp
#pragma once
#include "Object.hpp"
#include "Wire.hpp"
class Circuit : public Object
{
public:
Circuit(std::string name);
Wire* powerWire; // <- Error points to the beginning of this line
bool isPowered(Wire& wire);
bool getActive();
void setActive(bool active);
private:
bool active;
};
Circuit.cpp
#include "Circuit.hpp"
#include "Util.hpp"
Circuit::Circuit(string name) : Object(name + "-Circuit")
{
active = false;
powerWire = new Wire(name + "-PowerWire", this);
}
...
You haven't shown Wire.hpp, but my guess is that it includes Component.hpp, which gives you a cycle in header inclusion (because Component.hpp includes Circuit.hpp, and Circuit.hpp includes Wire.hpp).
You will have to replace some of these inclusions with forward declarations to break the cycle.
I am trying to make functions repository. I have created four files:
Function.hpp, Function.cpp, FunctionsRepository.hpp, FunctionsRepository.cpp
I want to keep pointers to functions in vector of pointers.
//FunctionsRepository.hpp
#ifndef FUNCTIONSREPOSITORY_HPP
#define FUNCTIONSREPOSITORY_HPP
#include <vector>
using namespace std;
class FunctionsRepository {
private:
static vector<double *> pointerToFunctions;
public:
static void addFunction(double * wsk);
};
#endif
//FunctionRepository.cpp
#include "FunctionsRepository.hpp"
void FunctionsRepository::addFunction(double * wsk) {
pointerToFunctions.push_back(wsk);
}
//Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTOINS_HPP
#include "FunctionsRepository.hpp"
int constFunction(int numberOfVehicles);
void linearFunction();
void stepFunction();
#endif
//Funcctions.cpp
#include "Functions.hpp"
double constFunction(double numberOfVehicles){
return numberOfVehicles/2;
}
double (*funcConstant)(double) = constFunction;
//ERROR HERE
FunctionsRepository::addFunction(funcConstant);
I want to add new functions to program as easily as its possible and use it leater in other parts of program.
But I dont get it. Why i am getting this error. The addFunction() method is static, that means I can use it in other classes or parts of program. Vector is static to make sure that is the only one copy for whole program.
Use function wrapper. std::function can stores callable objects. So, your code will contain something like this:
class FunctionsRepository {
private:
// void() - function prototype
static std::vector<std::function<void()>> pointerToFunctions;
public:
static void addFunction(std::function<void()> wsk)
{
pointerToFunctions.push_back(wsk);
}
};
for more information consult official documentation: http://en.cppreference.com/w/cpp/utility/functional/function
I solved It. I received an error because I was calling the FunctionsRepository::addFunction(funcConstant); expression out of any scope. I just created new function to execute this command and thats all.
Good day all
Please note: C++ newbie here
I am creating shared libraries among various other c++ features to allow for a complete understanding, however I am at a loss.
Problem:
As the title suggests, a list of errors:
I have no idea what causes them, and googling does not provide much insight either. As suggested here to add the Q_Object macro, I have done so but obviously it is of no use.
Various other SO posts suggest checking the correct header, etc which is correct.
Error:
netm.cpp:3: error: undefined reference to `vtable for netm'
netm.cpp:3: error: undefined reference to `_imp___ZN4miscC1Ev'
netm.cpp:6: error: undefined reference to `vtable for netm'
netm.cpp:6: error: undefined reference to `_imp___ZN4miscC1Ev'
//...
I have several more errors similar to these above, but solving these should assist me in resolving the rest
From all the tutorials, etc I have followed, I have done nothing out of the ordinary.
Note: I am unsure what information is all required, if more is required, I'll gladly share.
//.pro
QT -= gui
QT += network
TARGET = netm
TEMPLATE = lib
DEFINES += NETM_LIBRARY
SOURCES += netm.cpp
HEADERS += netm.h\
netm_global.h
unix {
target.path = /usr/lib
INSTALLS += target
}
//netm_global.h - FULL
#ifndef NETM_GLOBAL_H
#define NETM_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(NETM_LIBRARY)
# define NETMSHARED_EXPORT Q_DECL_EXPORT
#else
# define NETMSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // NETM_GLOBAL_H
//netm.h - FULL
#ifndef NETM_H
#define NETM_H
#include "netm_global.h"
#include "../misc/misc.h"
#include "../gen/gen.h"
#include <QHostInfo>
#include <QTcpSocket>
class NETMSHARED_EXPORT netm
{
Q_OBJECT
public:
netm();
netm(QString hostname);
bool Send(int portNumber, char* message = NULL);
ReturnObject read();
bool isServerOnline(QString IP = QString());
int getPing(QString IP = QString());
void getIP();
void disconnectFromServer();
~netm();
private slots:
void getIP();
private:
misc m;
QHostInfo serverInfo;
QHostAddress serverIP;
QTcpSocket tcp_con;
};
#endif // NETM_H
//netm.cpp - Partial
#include "netm.h"
netm::netm(){ <--- ERROR line
}
netm::netm(QString hostname) <--- ERROR line
{
serverInfo.lookupHost(hostname, 0, SLOT(getIP()));
}
//...
Help (with explanations) would be greatly appreciated!
UPDATE
As suggested, I defined the constructor in misc.cpp, since it was not present.
Recompiling, I read an error mentioning that the netm class needed to inherit from QObject.
Thus adding/changing:
//netm.h - Partial
#include //...
#include <QObject>
class NETMSHARED_EXPORT netm : public QObject
{
Q_OBJECT
public:
netm();
netm(QString hostname);
//...
};
Errors persist:
netm.cpp:3: error: undefined reference to `_imp___ZN4miscC1Ev'
netm.cpp:3: error: undefined reference to `_imp___ZN4miscD1Ev'
netm.cpp:6: error: undefined reference to `_imp___ZN4miscC1Ev'
netm.cpp:6: error: undefined reference to `_imp___ZN4miscD1Ev'
For completeness sake (misc is also a dynamic library):
//misc.h
#ifndef MISC_H
#define MISC_H
#include "misc_global.h"
#include <QString>
#include <QList>
class MISCSHARED_EXPORT misc
{
public:
misc();
~misc();
//String Literals
//Network related
static QString googleDNS;
//Command Codes
static QString CMD_AUTH;
static QString CMD_REQ;
//Request Codes
static QString REQ_USER_INFO;
static QString REQ_VPN_DATA;
static QString REQ_VPN_UP;
//...
};
//misc.cpp
#include "misc.h"
misc::misc(){
//Network related
QString googleDNS = QStringLiteral("8.8.8.8");
//Command Codes
QString CMD_AUTH = QStringLiteral("AUTH");
QString CMD_REQ = QStringLiteral("REQ");
//Request Codes
QString REQ_USER_INFO = QStringLiteral("USER_INFO");
QString REQ_VPN_DATA = QStringLiteral("VPN_DATA");
QString REQ_VPN_UP = QStringLiteral("VPN_UP");
}
misc::~misc(){}
As seen here, the constructor exists,
any other thoughts?
Missing calls to _imp___ZN4miscC1Ev, which is misc::misc() according to c++filt, likely means that the class misc is missing a defined default constructor. Check to make sure you're compiling in a definition for misc::misc().
For the vtable error, make sure that you've provided a definition (even if empty or stubbed out) for every function declared in netm (or at minimum all of the virtual functions in netm). The vtable for a class references every virtual function, so all of the virtual functions must be defined or it will not compile.
I would like to use one function from Stats.cpp in Application.cpp. Here are my code snippets:
In Stats.h:
#ifndef STATS_H
#define STATS_H
class Stats
{
public:
void generateStat(int i);
};
#endif
In Stats.cpp:
#include Stats.h
void generateStat(int i)
{
//some process code here
}
In Application.cpp:
int main()
{
generateStat(10);
}
I get an "unresolved external symbol" error however I don't know what I else I would need to include in order for Application.cpp. Any thoughts?
In Stats.cpp
you need to define generateStat like following :
#include Stats.h
void Stats:: generateStat(int i) // Notice the syntax, use of :: operator
{
//some process code here
}
Then create object of class Stats, use it to call the public member function generateStat
Stats s;
s.generateStat( 10 ) ;
Build the application using :
g++ -o stats Stats.cpp Application.cpp -I.
generateStat is part of your Stats class. You need to instantiate a Stats object (along with the necessary includes for Stats.h in your main class)
For example,
Stats stat;
stat.generateStat(i);
Also, your function definition needs to include the class name Stats::generateStat.
The same error msg occured 2 weeks ago (at work).
At first glance --- Try:
void Stats::generateStat(int i) {
//some process code here }
The class name was missing. Hence, unresolved.
btw Concerning your header --- another issue, this #ifndef directive should not be necessary cause you should declare Stats only once in a namespace.
#ifndef CLASS_H
#define CLASS_H
#include "Class.h"
#endif
This is a generic example - Usable in cpp files.
EDIT: Now, I saw your invocation (main method in your case). You need an object instance to invoke your method.
Stats* stats = new Stats(); //add a default constructor if not done
stats->generateStat(77);
// any other stats stuff ......
// in posterior to the last use
delete(stats);
In your header:
Stats::Stats(){}; //with an empty body - no need to write it again in the cpp file
Here's my code:
menuState.hpp
#ifndef MENU_STATE_HPP
#define MENU_STATE_HPP
#include "state.hpp"
#include <SFML/Graphics.hpp>
class MenuState : public State
{
public:
MenuState();
static void create(StateListener* Parent, const std::string name)
{
MenuState* myState = new MenuState();
myState->parent = Parent;
Parent->manageState(name, myState);
}
void enter();
void exit();
void resume();
private:
};
#endif // MENU_STATE_HPP
I'm getting an undefined reference to the constructor when I do MenuState* myState = new MenuState(); and I'm not sure why because MenuState::MenuState() comes before the create function in the class declaration.
EDIT: I'm also getting the same error to all my sfml functions.
Here's the exact build messages: http://pastebin.com/e819FhPj
I do have the sfml libraries linked and the header path set in my compilers search directories.
It is always best to show the exact text of the error, but my educated guess is, you are getting a linker error, not a compiler error. Have you actually implemented the constructor anywhere? I bet you haven't.
I'm not an experience C++ developer but it seems like MenuState constructor is declared but not defined.
Replace MenuState(); with MenuState(){} should fix the error.