0

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?

4

2 回答 2

2

这是一个链接器错误,链接器告诉您它找不到 class 的构造函数的定义Algorithms。你应该编译:

CC Algorithms.cc algo2.cc 

您可以识别它是链接器错误,因为错误ld:前面有。

当然,正如Kerrek SB所说,您需要在没有Algorithms::前面的情况下声明您的构造函数......

于 2012-09-03T07:53:11.113 回答
0

您刚刚忘记将两个 .cc 文件都包含在编译中:

cc algo2.cc Algorithms.cc

如果您包含带有声明的头文件,例如

#include "Algorithms.hh"

您还应该在 .c 或 .lib 中提供实现、定义。或动态加载带有定义的库。在您的情况下,您的库是 Algorithms.cc,因此只需将其添加到编译阶段,然后将两个临时目标文件添加到

Algo2.a + Algorithms.a

将会去

a.out
于 2012-09-03T08:02:39.983 回答