mercredi 30 août 2017

./libmylib.so: undefined reference to `submarinex::LIB::kCount'

I have 3 files in a directory. I will build ll.cc to libmylib.so, and build main.cc to myexe.

Use these command to build

g++ -Wall -g -fPIC -std=c++11 ll.cc -shared -o libmylib.so
g++ -Wall -g -std=c++11 main.cc -L. -lmylib -o myexe

But, g++ report a error when build myexe :

./libmylib.so: undefined reference to `submarinex::LIB::kCount'
collect2: error: ld returned 1 exit status

Files:

ll.h

namespace submarinex {

class LIB {
 public:
  void Print();

 private:
  // If remove 'static', it also be OK regardless of using
  // 'int min = std::min(101, kCount);
  // std::cout << min << std::endl;'
  // or
  // 'std::cout << kCount << std::endl;'
  static const int kCount = 100;
};

}  // namespace submarinex

ll.cc

#include "ll.h"

#include <algorithm>
#include <iostream>

namespace submarinex {

void LIB::Print() {
  int min = std::min(101, kCount);
  std::cout << min << std::endl;

  // If use this line, will success
  // std::cout << kCount << std::endl;
}

main.cc

#include "ll.h"

int main(int argc, char **argv) {
  submarinex::LIB lib;
  lib.Print();

  return 0;
}

Case 1: If use these 2 lines in Print, will report an error when link object of main.cc

  int min = std::min(101, kCount);
  std::cout << min << std::endl;

Case 2: If use this line in Print, will success

  std::cout << kCount << std::endl;

If change

 static const int kCount = 100;

to

 const int kCount = 100;

it also be OK regardless of using Case1 or Case2.

Aucun commentaire:

Enregistrer un commentaire