0

I have two files : a .cpp and a .hpp file. In the .hpp file there is a class with name Knoten and a public function definition :

static void faerbe_algorithmus(bool jsp[5][5], std::list< std::list<int> > &liste_von_str_orth_spalten); 

In the .cpp file I am trying to call the function in another function (compute_J) like this :

Knoten::faerbe_algorithmus(jsp, liste_von_str_orth_spalten); 

but I get the following error from g++ :

In function `compute_J(double*, double (*) [5])':
11_3.cpp:(.text+0x3fc): undefined reference to `Knoten::faerbe_algorithmus(bool (*) [5], std::list<std::list<int, std::allocator<int> >, std::allocator<std::list<int, std::allocator<int> > > >&)'
collect2: error: ld returned 1 exit status

What am I doing wrong? I can post more of the code, when needed.

kaloyant
  • 133
  • 3
  • 9

2 Answers2

1

Undefined reference often means that you have forgotten to add an implementation for the function you are trying to call.

For example:

Bad Foo.cpp

void doSomething();

int main()
{
    doSomething(); // undefined reference, there is no implementation
}

Good Foo.cpp

void doSomething();

int main()
{
    doSomething(); // this is OK, as the function is implemented later on
}

void doSomething()
{
    // insert code here
}

If you have implemented the function somewhere, check the the name is qualified correctly.

For example (applies to both namespaces and classes/structs):

MyClass.hpp

class MyClass
{
public:
    static void doSomething();
};

Bad MyClass.cpp

#include "MyClass.hpp"

void doSomething() // not qualified properly
{
    // insert code here
}

Good MyClass.cpp

#include "MyClass.hpp"

void MyClass::doSomething() // now qualified properly
{
    // insert code here
}
OMGtechy
  • 7,935
  • 8
  • 48
  • 83
0

undefined reference to Knoten::faerbe_algorithmus

Is the sign that you are missing the definition for the static public function. You either forgot to define it with:

void Knoten::faerbe_algorithmus(bool jsp[5][5], std::list< std::list<int> > &liste_von_str_orth_spalten) {
    // ...
}

or you are not linking the definition correctly.


On a side note, I'd suggest you to drop C-style arrays and start using std::array instead. It will save you a lot of troubles, especially with array to pointer decay. Here's the corresponding version:

void Knoten::faerbe_algorithmus(const std::array<std::array<bool, 5>, 5>& jsp, std::list< std::list<int> > &liste_von_str_orth_spalten) {
    // ...
}

I know it's probably harder to write, but you can create an alias to it:

template<class Type, std::size_t Size>
using bidim = std::array<std::array<Type, Size>, Size>

and use it like:

void Knoten::faerbe_algorithmus(const bidim<bool, 5>& jsp, std::list< std::list<int> > &liste_von_str_orth_spalten) {
    // ...
}
Shoe
  • 74,840
  • 36
  • 166
  • 272