This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
I've applied all the solutions provided by you for similar problems but I'm still getting this error:
undefined reference to `setgolf(golf&, char*, int)'
collect2: error: ld returned 1 exit status
here is the code header
#ifndef SANS_H_INCLUDED
#define SANS_H_INCLUDED
const int len = 40;
struct golf
{
char fullname[len];
int handicap;
};
//void setgolf(golf &,char * ,int);
int setgolf(golf &);
void sethandicap(golf &,int );
void showgolf(const golf &);
#endif
here is the file containing the functions definitions
#include <iostream>
#include <cstring>
#include "chapter9exe3.h"
void setgolf(golf & s,char *c ,int hc)
{
strcpy(s.fullname,c);
s.handicap=hc;
}
int setgolf(golf & s)
{
std::cin.getline(s.fullname,len);
if(s.fullname[0] == '\0'&& s.fullname[1] == '\0' && s.fullname[2] == '\0')
return 0;
else
return 1;
}
void sethandicap(golf & s,int n )
{
s.handicap = n;
}
void showgolf(const golf & s)
{
std::cout<<"the full name :"<<s.fullname<<std::endl;
std::cout<<"the handcape :"<<s.handicap<<std::endl;
}
here is the file containing the main function
#include <iostream>
#include "sans.h"
int main()
{
golf player;
char name[len] = "santers God's men";
int handicap = 84;
setgolf(player,name,handicap);
return 0;
}
Uncomment this:
//void setgolf(golf &,char * ,int);
in your header file, since you are doing in main:
setgolf(player,name,handicap);
which will search for a matching prototype in the header file, and will fail to fidn it, because you have commented it.
In other words, you call the function with three parameters, but only provide a prototype of this function in the header file with one parameter. As a result, the reference to setgolf() with three parameters is definetely undefined!
Related
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 6 years ago.
I have three c++ files, sort.cpp defines a bubble sort function that takes an array, the length of the array and a function that is used to do the comparison. sort.h contains the function prototype inside a namespace. main.cpp is used to test the implementation.
sort.h:
#ifndef SORT_H
#define SORT_H
namespace sort {
template <typename T>
void bubble(T*, int, bool (*)(T, T));
}
#endif
sort.cpp:
#include "sort.h"
template <typename T>
void sort::bubble(T *array, int length, bool (*compare)(T, T)) {
while (length != 0) {
int newLength {0};
for (int i {0}; i < length - 1; ++i) {
if (compare(array[i], array[i+1])) {
T temp {array[i]};
array[i] = array[i+1];
array[i+1] = temp;
newLength = i + 1;
}
}
length = newLength;
}
}
main.cpp:
#include <iostream>
#include "sort.h"
bool larger(int x, int y) {
return x > y;
}
int main() {
int arr[] {3, 5, 1, 3, 7, 2};
sort::bubble(arr, 6, larger);
for(const auto e: arr)
std::cout << e << ' ';
std::cout << '\n';
return 0;
}
When I compile with g++ main.cpp sort.cpp -std=c++11 I get the error
Undefined symbols for architecture x86_64:
"void sort::bubble<int>(int*, int, bool (*)(int, int))", referenced from:
_main in main-767bbd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Do I get the error because the compiler doesn't know which types I'm going to use when compiling sort.cpp? So the compiler doesn't generate any function off of the template and then the linker can't find it when I use it in main.cpp?
How can I solve this issue?
Don't use two files for templates, just only one: sort.hpp
There is a workaround but is not recommended.
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 7 years ago.
The solution to the duplicate question did not work
I have the following files:
ListaEnc.hpp
#include "Elemento.hpp"
template<typename T>
class ListaEnc {
public:
ListaEnc();
~ListaEnc();
// inicio
void adicionaNoInicio(const T& dado);
T retiraDoInicio();
void eliminaDoInicio();
T pegarHead();
// posicao
void adicionaNaPosicao(const T& dado, int pos);
int posicao(const T& dado) const;
T* posicaoMem(const T& dado) const;
bool contem(const T& dado);
T retiraDaPosicao(int pos);
// fim
void adiciona(const T& dado);
T retira();
// especifico
T retiraEspecifico(const T& dado);
void adicionaEmOrdem(const T& data);
// outras
bool listaVazia() const;
bool igual(T dado1, T dado2);
bool maior(T dado1, T dado2);
bool menor(T dado1, T dado2);
void destroiLista();
int pegarTamanhoLista();
private: //trocar pra private
Elemento<T>* head;
int size;
};
ListaEnc.cpp
#include "ListaEnc.hpp"
#include <cstdlib>
#include <iostream>
template<typename T>
ListaEnc<T>::ListaEnc()
{
...
}
main.cpp
#include "ListaEnc.hpp"
using namespace std;
int main(int argc, char** argv)
{
double x1, y1;
x1 = 2; y1 = 4.2;
ListaEnc<int>* teste = new ListaEnc<int>();
return 0;
}
This should compile just fine, but I get an undefined reference error to ListaEnc on main.cpp. I have more files in which the reference to ListaEnc is also undefined, but I tried isolating it and still can't get it to work. Does anyone understand why this is happening?
edit: More specifically, there is an undefined error to the constructor and destructor of ListaEnc
You can't separate declaration from implementation when you instantiate a template class. Combine your code to a single file and include that in your main.cpp.
Or, even go a step further and implement the functions inline in your class declaration if that suits your coding style.
Noobie programmer here learning C++ for the first time. The following is excerpted code from Teach Yourself C++ 3rd Edition.
I'm dying help me, I'm learning about classes, but I can't get this code to compile on visual studio or on Code::Blocks. :(
//#include "stdafx.h"
#include <iostream>
//I understand this. Headers, etc.
using namespace std;
//and this, name traffic management system
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a();
};
/*I understand int a is private/inaccessible from the rest of the code
and void set_a(int num) is the dummy function.*/
void myclass::set_a(int num)
//not sure what this is
{
a = num;
}
/*self explanatory*/
int _tmain(int argc, _TCHAR* argv[])
{
myclass ob1, ob2;
ob1.set_a(10);
ob2.set_a(99);
cout << ob1.get_a() << "\n";
cout << ob2.get_a() << "\n";
return -5;
}
/*This is just supposed to output the number 10 and 99 right?? So why isn't it?*/
On Visual Studio the full error description is:
Error 1 error LNK2019: unresolved external symbol "public: int __thiscall myclass::get_a(void)" (?get_a#myclass##QAEHXZ) referenced in function _wmain c:\Users\bernardo pliego\documents\visual studio 2013\Projects\Chapter 1.5\Chapter 1.5\Chapter 1.5.obj Chapter 1.5
On Code::Blocks I receive the following error:
In function 'main':
undefined reference to 'my_class::get_a()'
I am in dire need of help, can someone explain this to me?
Because you don't define get_a, you only declare it. Add a definition like this:
int myclass::get_a() { return a; }
Or just define it inline:
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a() { return a };
};
You don't ever define int get_a(); so you get an error at link-time.
Include this just above your (rather hubristic) /*self explanatory*/ comment
int myclass::get_a()
{
return a;
}
i'm trying to create a library with some functions I often use, but compiling I have this error:
Torri_lib.cpp||multiple definition of `inizRandVett(int*, int, int, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `printVett(int*, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `scambio(int*, int*)'|
Torri_lib.cpp||first defined here|
||=== Build finished: 6 errors, 0 warnings (0 minutes, 0 seconds) ===|
This is the main.cpp:
#include <iostream>
#include "Torri_lib.h"
#define N 10
using namespace std;
void ordina(int*,int);
int main()
{ int vett[N];
srand(time(NULL));
inizRandVett(vett,N,-20,20);
printf("Vettore generato:\n");
printVett(vett,N);
ordina(vett,N);
printf("\n\nVettore ordinato (neg a sx, pos a dx):\n");
printVett(vett,N);
printf("\n\n");
return 0;
}
void ordina(int*vett,int dim)
{ int i,j,neg=0,pos=0;
for(i=0;i<dim;i++)
if(vett[i]<0)
neg++;
else
pos++;
for(i=0,j=neg;i<neg;i++)
if(vett[i]>=0){
while(vett[++j]>=0);
scambio(&vett[i],&vett[j]);
}
}
This is Torri_lib.cpp:
#include <iostream>
#include"Torri_lib.h"
void inizRandVett(int *vett, int dim, int rangeMin, int rangeMax)
{ int i;
for(i=0;i<dim;i++)
vett[i]=rand()%(rangeMax-rangeMin)+rangeMin;
}
void printVett(int *vett, int dim)
{ int i;
for(i=0;i<dim;i++)
printf("%d ",vett[i]);
}
void scambio(int*var1,int*var2)
{
int temp=*var1;
*var1=*var2;
*var2=temp;
}
And this is Torri_lib.h :
void inizRandVett(int*, int, int, int );
void printVett(int *, int);
void scambio(int*,int*);
I don't understand why it says me this error, I don't see multiple definition of the functions.
Can you help me? Thanks!
Maybe you didn't put a guard in your .h file?
Try putting at the beginning of the file:
#ifndef TORRI_H_INCLUDED
#define TORRI_H_INCLUDED
and at the end:
#endif
You need to write in header file to prevent multiple declaration:
#pragma once
// code
OR
#ifndef NAME_H_
# define NAME_H_
// code
#endif
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
Error 1 error LNK2019: unresolved external symbol "bool __cdecl
prefix(unsigned int,unsigned int)" (?prefix##YA_NII#Z) referenced in
function _main c:\Users\Work\documents\visual studio
2012\Projects\Book\Project5\Project5\Source.obj Project5
Error 2 error LNK1120: 1 unresolved
externals c:\users\work\documents\visual studio
2012\Projects\Book\Project5\Debug\Project5.exe 1 1 Project5
I just..I dont even know what I have to ask you guys. How do I fix this?
This is the code:
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
using namespace std;
void citire(vector<unsigned int> myVector,int &nrElem);
bool prefix(unsigned int nr1,unsigned int nr2);
int main(){
int nrElem={0};
vector<unsigned int> myVector;
//citire(myVector,nrElem);
cout << prefix(123,1234);
system("pause");
return 0;
}
void citire(vector<unsigned int> myVector,int &nrElem){
cout << "NumarElemente=" ;
cin >> nrElem ;
for(int i=0;i<nrElem;i++){
unsigned int nrCitit;
cout << "Elem #" << i+1 <<"=";
cin >> nrCitit;
myVector.push_back(nrCitit);
};
for(int i=0;i<nrElem;i++){
cout << myVector.at(i);
};
}
bool prefix(unsigned int &nr1,unsigned int &nr2){
unsigned int nr1copy=nr1;
unsigned int nr2copy=nr2;
int digitsNr1 = 0; while (nr1copy != 0) { nr1copy /= 10; digitsNr1++; }
int digitsNr2 = 0; while (nr2copy != 0) { nr2copy /= 10; digitsNr1++; }
if ( nr2/_Pow_int(10,digitsNr2-digitsNr1)==nr1) {return true;}
else return false;
}
bool prefix(unsigned int nr1,unsigned int nr2);
is not same as
bool prefix(unsigned int& nr1,unsigned int &nr2);
In forward forward declaration, you are taking the parameters by value but in the definition it is by reference. Keep the argument types same in the declaration and the definition.
unresolved external symbol "bool __cdecl prefix(unsigned int,unsigned int)"
Usually when you see these kind of linker errors, the first thing you need to check is if the function's declaration and definition signatures match or not. In this case, it is clearly not.
Declaration:
bool prefix(unsigned int nr1,unsigned int nr2);
definition:
bool prefix(unsigned int &nr1,unsigned int &nr2){ ... }
See the difference? Both should be the same. Looking at your code, it looks like you should keep the version in the declaration.
You have a prototype for the prefix() function:
bool prefix(unsigned int nr1,unsigned int nr2);
which has a signature that differs from the implementation given below:
bool prefix(unsigned int &nr1,unsigned int &nr2) {
^^^ ^^^
....
}
Note that in the prototype, the nr1 and nr2 parameters are passed by value; instead, in the implementation signature, they are passed by reference (note the &).
Both prototype and implementation signatures should match. Fix the wrong one.
(Note: since you can't pass literals like the 123 in main() as non-const reference, I think the wrong one is the implementation signature, i.e. drop the & in the implementation signature).