Undefined Reference issue with C++ and Netbeans - c++

I have the following files:
ListaEnc.hpp
#include "Elemento.hpp"
#include <cstdlib>
#include <iostream>
template<typename T>
class ListaEnc {
public:
ListaEnc();
~ListaEnc();
...
}
//Implementation:
template<typename T>
ListaEnc<T>::ListaEnc()
{
head = NULL;
size = 0;
}
template <class T>
ListaEnc<T>::~ListaEnc() {
}
main.cpp:
#include "ListaEnc.hpp"
using namespace std;
int main(int argc, char** argv)
{
ListaEnc<int>* teste = new ListaEnc<int>();
return 0;
}
Poligono.hpp
#ifndef POLIGONO_HPP
#define POLIGONO_HPP
#include "Ponto.hpp"
#include "ListaEnc.hpp"
#include <string>
using namespace std;
public:
//Construtores
Poligono(ListaEnc<Ponto> pontos, string nome);
Poligono(const Poligono& orig);
virtual ~Poligono();
//Metodos
string obterNome();
void adicionarPonto(Ponto);
ListaEnc<Ponto> obterPontos();
private:
ListaEnc<Ponto> pontos;
string nome;
};
#endif /* POLIGONO_HPP */
Poligono.cpp
#include "Poligono.hpp"
* Poligono::Poligono(ListaEnc<Ponto> pontos, string nome)
{
this->pontos = pontos;
this->nome = nome;
}
* Poligono::Poligono(const Poligono& orig) {
}
* Poligono::~Poligono() {
}
//Metodo
string Poligono::obterNome()
{
return this->nome;
}
ListaEnc<Ponto> Poligono::obterPontos()
{
return this->pontos;
}
void Poligono::adicionarPonto(Ponto p)
{
this->pontos.adiciona(p);
}
I get these compile errors on Poligono.cpp:
/home/mariana/NetBeansProjects/TrabalhoCG/Poligono.cpp:12: undefined reference to `ListaEnc::~ListaEnc()'
The destructor for ListaEnc is empty, but is implemented. Does anyone know how to solve this problem?
Edit: Added the implementation of constructor and destructor for ListaEnc. The error appears in the bit of code I added for Poligono.cpp, where ListaEnc is one of the parameters.
Edit2: I have added an asterisk to the points in Poligono.cpp where the error appears (The first constructor, second constructor and destructor)

Since you posted code that shows
#ifndef POLIGONO_HPP
#define POLIGONO_HPP
in Poligono.cpp, but you don't have the same in ListaEnc.hpp, I assume that you are missing include guards in that header?
Depending on what other code is included in Poligono.cpp, this could result in the definition of template ListaEnc twice. Under C++ standard if you break the one definition rule you may just get a linking error and no other diagnostic message.
So, maybe make sure that there are include guards in ListaEnc.hpp ?
If you post more code I will update this answer :)
Edit: Another suggestion, if it is having trouble finding the dtor definition of ListaEnc, you might try moving the implementation of it into the class body? This makes it less likely that a typo will cause it to be lost. Since all the code is in the header this really doesn't change anything otherwise.

Related

C++ circular dependency, undeclared identifier

I have to class that use each other but whatever I tried I couldn't achieve to make them work.
I just want them to access each other and after days of struggle, I decided to ask here.
If someone can point out what I am doing wrong and what I should do instead it would be great.
Edit: I decided to implement one of the solutions which are already on stack overflow and changed my code according to that:
I will also share errors this time so maybe we can figure out what's wrong.
I tried to copy this:
Resolve build errors due to circular dependency amongst classes
I used class name "Unit" instead of "A" and "Skill" instead of
"B"
Skill.h
#pragma once
#include <iostream>
#include <vector>
#include "Unit.h"
using namespace std;
class Skill :
public Unit
{
double _val;
Unit* unitPtr;
public:
Skill(double val):_val(val)
{
}
void SetSkill(Unit* unit)
{
unitPtr = unit;
unitPtr->Print();
}
void Print()
{
cout << "Type:B val=" << _val << endl;
}
// Unit* unitPtr;
vector <Skill *> attacks;
vector <Skill *> utilities;
vector <Skill *> movement;
};
Unit.h
#pragma once
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Skill;
class Unit
{
int _val;
Skill* skillPtr;
public:
Unit(int val) :_val(val)
{
stunned = false;
curSpeed = speed + rand() % 8 + 1;
}
void SetSkill(Skill* skill)
{
skillPtr = skill;
skillPtr->Print(); // COMPILER ERROR: C2027: use of undefined type 'B'
}
void Print()
{
cout << "Type:A val=" << _val << endl;
}
int GetDodge()
{
return dodge;
}
void Setup();
string name;
int maxHP;
//... and other variables
};
Unit.cmp
#include "Skill.h"
#include "Unit.h"
void Unit::Setup()
{
heroes.push_back(new Vestal);
heroes.push_back(new Vestal);
heroes.push_back(new Crusader);
heroes.push_back(new Crusader);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
monsters.push_back(new BoneSoldier);
monsters.push_back(new BoneDefender);
}
Later on the code, I add some stuff to attacks, utilities, and moment and I want to access them from the Unit object, like below:
heroes[0]->skillPtr->attacks[0]
And I want to be able to access the variables in the Unit.h (like maxHP) from Skill.h
Errors:
Error C2512 'Skill': no appropriate default constructor available
Error C2512 'Unit': no appropriate default constructor available
I'm a beginner but maybe I can see a couple of issues that are likely causing you problems here.
First you've got a classic circular dependency here, Unit.h includes Skill.h which includes Unit.h which includes Skill.h and so on.
Secondly not seeing any #pragma once pre-proccessor directives. Which means when you then go on to try and include both Skill.h and Unit.h in your unit CPP file, you will try to include the .h files more than once, as they include each other...
Thirdly you're using namespace std in the global scope. You can do that, but don't do that.
If you're looking for more try this excellent video on the subject
https://www.youtube.com/watch?v=Zbw58vTotok

initializing a static (non-constant) variable of a class.

I have TestMethods.h
#pragma once
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
class TestMethods
{
private:
static int nextNodeID;
// I tried the following line instead ...it says the in-class initializer must be constant ... but this is not a constant...it needs to increment.
//static int nextNodeID = 0;
int nodeID;
std::string fnPFRfile; // Name of location data file for this node.
public:
TestMethods();
~TestMethods();
int currentNodeID();
};
// Initialize the nextNodeID
int TestMethods::nextNodeID = 0;
// I tried this down here ... it says the variable is multiply defined.
I have TestMethods.cpp
#include "stdafx.h"
#include "TestMethods.h"
TestMethods::TestMethods()
{
nodeID = nextNodeID;
++nextNodeID;
}
TestMethods::~TestMethods()
{
}
int TestMethods::currentNodeID()
{
return nextNodeID;
}
I've looked at this example here: Unique id of class instance
It looks almost identical to mine. I tried both the top solutions. Neither works for me. Obviously I'm missing something. Can anyone point out what it is?
You need to move the definition of TestMethods::nextNodeID into the cpp file. If you have it in the header file then every file that includes the header will get it defined in them leading to multiple defenitions.
If you have C++17 support you can use the inline keyword to declare the static variable in the class like
class ExampleClass {
private:
inline static int counter = 0;
public:
ExampleClass() {
++counter;
}
};

Include issue: 'multiple definition', 'first defined here'

I have three files:
main.cpp
MyClass.cpp
MyClass.hpp
I have a library header file, "testLib.hpp", that I want to include in MyClass.hpp so that I can have one of testLib's objects be a class attribute.
I include MyClass.hpp in MyClass.cpp and in main.cpp. When attempting to compile the project, I get the following errors
MyClass.cpp multiple definition of 'testLib::testLib::function1()
obj/Release/main.o:main.cpp first defined here
MyClass.cpp multiple definition of 'testLib::testLib::function2()
obj/Release/main.o:main.cpp first defined here
and so on.
Both main.cpp and MyClass.cpp include MyClass.hpp (which includes testLib.hpp). Judging by the error, it looks like MyClass.cpp is attempting to include the library functions after they've already been included by main.cpp. However, I have include guards present in MyClass.hpp so I don't understand how it's trying to include MyClass.hpp twice.
Here's the code:
MyClass.hpp
#ifndef THIS_HEADER_H
#define THIS_HEADER_H
#include <stdint.h>
#include <iostream>
#include "testLib/testLib.hpp"
class MyClass
{
public:
void test();
int foo;
private:
uint32_t bar;
//I want to include an object from the library as part of this class
//TestLib::Device device;
};
#endif
MyClass.cpp
#include <stdio.h>
#include "MyClass.hpp"
void MyClass::test()
{
}
main.cpp
#include <iostream>
#include "MyClass.hpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Any help would be greatly appreciated!
EDIT
I tried to hide the actual filenames to make the question more general and clear, but it seems like the problem might be resulting from 'testLib.hpp', which I did not write. That file is actually the following "sweep.hpp" file. I got the 'multiple definition of/first defined here' errors for each of the public functions in this file:
sweep.hpp
#ifndef SWEEP_DC649F4E94D3_HPP
#define SWEEP_DC649F4E94D3_HPP
/*
* C++ Wrapper around the low-level primitives.
* Automatically handles resource management.
*
* sweep::sweep - device to interact with
* sweep::scan - a full scan returned by the device
* sweep::sample - a single sample in a full scan
*
* On error sweep::device_error gets thrown.
*/
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <vector>
#include <sweep/sweep.h>
namespace sweep {
// Error reporting
struct device_error final : std::runtime_error {
using base = std::runtime_error;
using base::base;
};
// Interface
struct sample {
const std::int32_t angle;
const std::int32_t distance;
const std::int32_t signal_strength;
};
struct scan {
std::vector<sample> samples;
};
class sweep {
public:
sweep(const char* port);
sweep(const char* port, std::int32_t bitrate);
void start_scanning();
void stop_scanning();
bool get_motor_ready();
std::int32_t get_motor_speed();
void set_motor_speed(std::int32_t speed);
std::int32_t get_sample_rate();
void set_sample_rate(std::int32_t speed);
scan get_scan();
void reset();
private:
std::unique_ptr<::sweep_device, decltype(&::sweep_device_destruct)> device;
};
// Implementation
namespace detail {
struct error_to_exception {
operator ::sweep_error_s*() { return &error; }
~error_to_exception() noexcept(false) {
if (error) {
device_error e{::sweep_error_message(error)};
::sweep_error_destruct(error);
throw e;
}
}
::sweep_error_s error = nullptr;
};
}
sweep::sweep(const char* port)
: device{::sweep_device_construct_simple(port, detail::error_to_exception{}), &::sweep_device_destruct} {}
sweep::sweep(const char* port, std::int32_t bitrate)
: device{::sweep_device_construct(port, bitrate, detail::error_to_exception{}), &::sweep_device_destruct} {}
void sweep::start_scanning() { ::sweep_device_start_scanning(device.get(), detail::error_to_exception{}); }
void sweep::stop_scanning() { ::sweep_device_stop_scanning(device.get(), detail::error_to_exception{}); }
bool sweep::get_motor_ready() { return ::sweep_device_get_motor_ready(device.get(), detail::error_to_exception{}); }
std::int32_t sweep::get_motor_speed() { return ::sweep_device_get_motor_speed(device.get(), detail::error_to_exception{}); }
void sweep::set_motor_speed(std::int32_t speed) {
::sweep_device_set_motor_speed(device.get(), speed, detail::error_to_exception{});
}
std::int32_t sweep::get_sample_rate() { return ::sweep_device_get_sample_rate(device.get(), detail::error_to_exception{}); }
void sweep::set_sample_rate(std::int32_t rate) {
::sweep_device_set_sample_rate(device.get(), rate, detail::error_to_exception{});
}
scan sweep::get_scan() {
using scan_owner = std::unique_ptr<::sweep_scan, decltype(&::sweep_scan_destruct)>;
scan_owner releasing_scan{::sweep_device_get_scan(device.get(), detail::error_to_exception{}), &::sweep_scan_destruct};
auto num_samples = ::sweep_scan_get_number_of_samples(releasing_scan.get());
scan result;
result.samples.reserve(num_samples);
for (std::int32_t n = 0; n < num_samples; ++n) {
auto angle = ::sweep_scan_get_angle(releasing_scan.get(), n);
auto distance = ::sweep_scan_get_distance(releasing_scan.get(), n);
auto signal = ::sweep_scan_get_signal_strength(releasing_scan.get(), n);
result.samples.push_back(sample{angle, distance, signal});
}
return result;
}
void sweep::reset() { ::sweep_device_reset(device.get(), detail::error_to_exception{}); }
} // ns
#endif
A simplified version of your problem:
buggy.hpp
int function() { return 0; }
main.cpp
#include "buggy.hpp"
int main() { return 0; }
other.cpp
#include "buggy.hpp"
The problem is that buggy.hpp is defining function, not just declaring. Once the header inclusion is expanded, that means function is declared in both main.cpp and other.cpp - and that is not allowed.
The fix is to declare function as inline which allows the function to be declared in multiple translation units.
inline int function() { return 0; }
In fact, allowing multiple definitions is the only meaning of inline to the C++ standard. Compilers may treat it as a hint that the function body may be expanded inline. Good ones won't; they are better at making that sort of decision that programmers).

C++ Linked Lists with struct

I'm new in C++ and I have something to do with a linked list, and I don't know why it doesn't work, need help from a prof :O)
Here's my .h
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
struct Thecube;
private:
void PrintList();
};
#endif
My ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
struct Thecube{
int base;
int cube;
Thecube * next ;
};
void ACube::PrintList(){
};
and finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = (ACube*)malloc(sizeof(ACube));
for (int inc=1; inc <=20 ; inc++){
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Everything was working fine, but when I add these lines :
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
I add error saying :
'class ACube' has no member named 'TheCube'
'class ACube' has no member named 'cube'
Can someone help me because I want to create my list and fill the cube with number.
Other thing I want to use THIS. in the print,
Maybe someone can teach me what's wrong and how to do it !
Thanks for any help
You don't need to have a struct inside your class.
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
int base;
int cube;
ACube * next ;
private:
void PrintList();
};
#endif
ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
void ACube::PrintList(){
};
Also, this string is wrong:
temp->ACube->nombrebase = inc;
it should be just:
temp->base = inc;
Last but not least, this code doesn't create a linked list, because you don't do anything with the ACube::next pointer.
There are so many horrible problems in your code, I suggest you should learn more C++ knowledge before writing linked list.
1. What is nombrebase?
I think nobody can answer.
2. You must allocate C++ class by new key word instead of malloc.
new invokes not only allocation but also class constructor, while malloc allocates only.
3. Thecube should been defined inside ACube
Since the code in your main() refers the member cube in class Thecube, main() must know what it is.
4. The member next in class ACube is a pointer which points to what?
What does a pointer point to without initilization? You should initial it in constructor, and destroy it in destructor.
5. temp->ACube
ACube is a class type, you can access member object, but not a type.
6. Never using namespace into a header file
It would make the client of header file has name collision.
The following is the corrected code. Just no compile error and runtime error, but this is NOT linked list:
ACube.h
#ifndef UnCube_H
#define UnCube_H
class ACube{
public:
struct Thecube
{
int base;
int cube;
Thecube * next;
};
ACube();
~ACube();
Thecube *next;
private:
void PrintList();
};
#endif
ACube.cpp
ACube::ACube()
: next(new Thecube)
{
}
ACube::~ACube()
{
delete next;
}
void ACube::PrintList(){
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = new ACube;
for (int inc = 1; inc <= 20; inc++)
{
temp->next->base = inc; // <-- This is not linked list, you shall modify.
temp->next->cube = inc*inc*inc; // <-- This is not linked list, you shall modify.
}
system("PAUSE");
return EXIT_SUCCESS;
}

No Matching Function Call

I'm new to C++ and trying to code a HashTable data structure.
I've written it to be generic using templates, and I've included a HashEntry object to use in it to allow for easy quadratic probing for collisions.
The code I have is:
(in a .C file that #include's the below class definition .H file):
HashEntry::HashEntry()
{
this->isActive = false;
}
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
using namespace std;
#define Default_Size 50000
class HashEntry;
template <class T> class HashTable
{
private:
int size;
int occupied;
T array[Default_Size];
public:
HashTable();
int Size();
void Add(T t);
void DebugAdd(T t, int index);
T* Get(string index);
/* How do I declare the existence of HashEntry BEFORE here? */
int FindNextOpen(HashEntry he); // Only works for hash_entry objects!
int Hash(string str);
void Rehash();
};
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry();
HashEntry(Entry e);
bool IsActive();
Entry GetEntry();
};
Whenever I try and compile everything, I get the error for the HashEntry constructor above:
"no matching function for call to Entry::Entry()" ... "candidates are.....".
I have no idea what it means -- when I try to include a default Entry() constructor (my first interpretation), it throws more errors.
Thanks for the help!
UPDATE -- ENTRY.C:
#include "Entry.H"
/* ***Entry Methods*** */
/*
* Overloaded Entry obejct constructor that provides a string value.
*/
Entry::Entry(string s)
{
this->value = s;
this->count = 0;
}
/*
* Returns the number of times this Entry has been accessed/
* found.
*/
int Entry::Count()
{ return this->count; }
/*
* Returns the string value stored in the Entry object.
*/
string Entry::Value()
{ return this->value; }
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
Whoa! Never, ever #include a source file in a header.
Your Entry.C should not exist. Instead define the constructor in your header, inside the class definition:
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry() : isActive(true) {}
...
}
One thing that you haven't shown us is the definition of the class Entry. That is one of the sources of your problem. It's a bit hard to pin down your problem when you didn't show us the very thing that is causing it.
I found the problem.
The error message says there is not matching function call for "Entry::Entry()". Because in no case was I actually creating Entry objects I had no idea what it meant.
I tried adding an explicit default constructor for class Entry and it resolved.
Thanks for the help everyone!