我在目录中有3个文件。我将建立ll.cc
至libmylib.so
,并建立main.cc
至myexe
。./libmylib.so:对'submarinex :: LIB :: kCount'的未定义引用
使用以下命令来构建
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
但是,G ++报告一个错误,当构建myexe
:
./libmylib.so: undefined reference to `submarinex::LIB::kCount'
collect2: error: ld returned 1 exit status
文件:
ll.h
namespace submarinex {
class LIB {
public:
void Print();
private:
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;
// std::cout << kCount << std::endl;
}
} // namespace submarinex
main.cc
#include "ll.h"
int main(int argc, char **argv) {
submarinex::LIB lib;
lib.Print();
return 0;
}
Case 1
: 如果Print
使用这2条线路,将报告一个错误,当main.cc
int min = std::min(101, kCount);
std::cout << min << std::endl;
Case 2
的链接对象: 如果在Print
中使用此行,将成功
std::cout << kCount << std::endl;
如果改变
static const int kCount = 100;
到
const int kCount = 100;
也没事,无论使用Case1
或Case2
的。
我不知道如何解决这个问题。