libxx.so: undefined reference, vector.reserve(n)

background: Trying to avoid reallocation using the STL: std::vector.reserve(n). 

在class AngleCal中声明了static std::vector sample_num, 并想要在AngleCal::AngleCal()中进行sample_num.reserve(300) (assumming 300 is the size or, alternatively an upper bound on the size)

libxx.so: undefined reference, vector.reserve(n)_第1张图片

libxx.so: undefined reference, vector.reserve(n)_第2张图片

但是在将此AngleCal.cpp编译成libanglecal.so时编译器给出了如下报错:

[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::if_first_detection'

[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::sample_num'

[build] /usr/bin/ld: ../lib/libanglecal.so: undefined reference to `hitcrt::AngleCal::i'

【解决办法】:A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

#include 
 
using namespace std;

class Box {
   public:
      static int objectCount;
      
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         
         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

运行结果为:

Constructor called.
Constructor called.
Total objects: 2

static修饰的类成员必须先在class外部initialize,然后才能对其操作。

libxx.so: undefined reference, vector.reserve(n)_第3张图片

以上。

你可能感兴趣的:(c++,c++,linux)