编写code
结构如下:
非主目录
(下面三个代码 SoTest.h SoTest.cpp test.cpp 是在001的文件夹下,非主目录)
SoTest.h
#ifndef INC_0303_SOTEST_H
#define INC_0303_SOTEST_H
class SoTest {
public:
void func1();
virtual void func2();
virtual void func3()=0;
};
#endif //INC_0303_SOTEST_H
SoTest.cpp
#include<iostream>
#include "SoTest.h"
void SoTest::func1(){
printf("func1\n");
};
void SoTest::func2(){
printf("func2\n");
};
test.cpp
#include <iostream>
#include "SoTest.h"
class Test:public SoTest{
public:
void func2(){
printf("test-func2\n");
}
void func3(){
printf("test-func3\n");
}
};
int main() {
Test t1;
t1.func1();
t1.func2();
t1.func3();
return 0;
}
编译动态库
g++ -shared -fPIC SoTest.cpp -o libSoTest.so
测试动态库
g++ test.cpp -lSoTest -L./ -o test
主目录
(主目录)
SoTest.h
#ifndef INC_0303_SOTEST_H
#define INC_0303_SOTEST_H
class SoTest {
public:
void func1();
virtual void func2();
virtual void func3()=0;
};
#endif //INC_0303_SOTEST_H
main.cpp
#include <iostream>
#include "SoTest.h"
class MyTest:public SoTest{
public:
void func2(){
printf("main-func2\n");
}
void func3(){
printf("main-func3\n");
}
};
int main() {
MyTest t1;
t1.func1();
t1.func2();
t1.func3();
return 0;
}
编译 main.cpp 后 运行 发现找不到 libSoTest.so的动态库
编译过程:
g++ main.cpp -lSoTest -L./001 -o main
解决方案如下:
1 动态库编译完成之后要发布,否则程序运行时找不到
Linux 默认动态库路径配置文件
/etc/ld.so.conf /etc/ld.so.conf.d/*.conf
/usr/lib
/usr/local/lib
2 运行时手动指定动态库目录
//mac
DYLD_LIBRARY_PATH=./001
export DYLD_LIBRARY_PATH
//linux
LD_LIBRARY_PATH=./001
export LD_LIBRARY_PATH
实践证明 自己生成的动态库需要 复制到 ubuntu 的 /usr/lib
下才会识别, 在 /usr/local/lib 下不能
第一种: 放在系统内可识别位置
第二种:手动指定