Vijay
Vijay

Reputation: 67211

Compiler error undefined symbol

I have simple class ina header file:

> cat Algorithms.hh
#ifndef Algorithms_hh
#define Algorithms_hh
#include<vector>
class Algorithms
{
public:

Algorithms();
void BubbleSort();

std::vector<int> myarray;

};
#endif

Then a corresponding c file:

> cat Algorithms.cc
#include <iostream>
#include <vector>
#include "Algorithms.hh"

Algorithms::Algorithms()
{
myarray.push_back(0);
}


void Algorithms::BubbleSort()
{
      int i, j, flag = 1;    // set flag to 1 to start first pass
      int temp;             // holding variable
      int numLength = myarray.size(); 
      for(i = 1; (i <= numLength) && flag; i++)
     {
          flag = 0;
          for (j=0; j < (numLength -1); j++)
         {
               if (myarray[j+1] > myarray[j])      // ascending order simply changes to <
              { 
                    temp = myarray[j];             // swap elements
                    myarray[j] = myarray[j+1];
                    myarray[j+1] = temp;
                    flag = 1;               // indicates that a swap occurred.
               }
          }
     }
}
>

And then the main function:

> cat algo2.cc
#include <iostream>
#include <vector>
#include "Algorithms.hh"

using namespace std;

int main(int argc,char **argv)
{

Algorithms *arr=new Algorithms();
arr->myarray.push_back(1);
arr->myarray.push_back(2);
arr->myarray.push_back(100);
return 0;
}

> 

When i compile the main: I get the below error:

> CC algo2.cc 
Undefined                       first referenced
 symbol                             in file
Algorithms::Algorithms()              algo2.o
ld: fatal: Symbol referencing errors. No output written to a.out

Can anyone tell me where i am wrong?

Upvotes: 0

Views: 1613

Answers (2)

blackbada_cpp
blackbada_cpp

Reputation: 432

You've just forgotten to include both .cc files into compiling:

cc algo2.cc Algorithms.cc

If you include header file with declarations, like

#include "Algorithms.hh"

you should also provide implementation, definition in .c, or .lib. or load library with definition dynamically. In your case your library is Algorithms.cc, so just add it into compilation stage, and then both temporary object files

Algo2.a + Algorithms.a

will go to

a.out

Upvotes: 0

DipSwitch
DipSwitch

Reputation: 5640

This is a linker error, the linker is telling you it can't find the definition of constructor of class Algorithms. You should compile with:

CC Algorithms.cc algo2.cc 

You can identify it's a linker error because of the ld: in front of the error.

And of course as stated by Kerrek SB you need to declare your constructor without the Algorithms:: in front of it...

Upvotes: 2

Related Questions