动态库和静态库
1.制作并使用静态库
静态链接:在生成可执行文件的时候将静态库的代码复制一份到可执行文件中。
优点:运行时速度快
缺点:程序体积更大,并且静态库中的内容如果有更新,则需要重新编译生成程序。
代码结构
.
├── include
│ └── test.h
├── static_library
│ ├── libtest.a
│ ├── makefile
│ └── test.cpp
└── test_static_library
├── main
├── main.cpp
└── makefile
源代码
include/test.h
class CTestLib {
public:
void func();
};
static_library/makefile
TARGET = test
HEADPATH = ../include/
CXX = g++
all:
$(CXX) -c $(TARGET).cpp -o $(TARGET).o -I $(HEADPATH)
$(AR) -r lib$(TARGET).a $(TARGET).o
rm $(TARGET).o
clean:
rm *.a
static_library/test.cpp
#include<iostream>
#include "../include/test.h"
void CTestLib::func() {
printf("Hello, I am func\n");
}
test_static_library/makefile
TARGET = main
#指定静态库的路径和头文件的路径
LDFLAGS = -L ../static_library/ -I ../include/
#指定在生成可执行文件时需要的静态库
LIBS = -static -ltest
CXX = g++
$(TARGET):
$(CXX) -o $(TARGET) $(TARGET).cpp $(LIBS) $(LDFLAGS)
clean:
rm $(TARGET)
test_static_library/main.cpp
#include<iostream>
#include "../include/test.h"
int main()
{
CTestLib test;
test.func();
}
制作静态库
- 进入目录
static_library
:执行命令
make
生成静态库文件libtest.a
,文件结构变成:
.
├── libtest.a
├── makefile
└── test.cpp
使用静态库
- 进入目录
test_static_library
:执行命令
make
生成可执行文件main
,文件目录变成:
.
├── main
├── main.cpp
└── makefile
- 然后执行main
./main
结果:
Hello, I am func
2.制作并使用动态库
代码结构
.
├── dynamic_library
│ ├── libtest.so
│ ├── makefile
│ └── test.cpp
├── include
│ └── test.h
└── test_dynamic_library
├── main.cpp
└── makefile
源代码
include/test.h
class CTestLib {
public:
void func();
};
dynamic_library/makefile
TARGET = test
# 头文件路径
HEADPATH = ../include/
CXX = g++
CXXFLAGS = -c -fPIC
all:
$(CXX) $(CXXFLAGS) $(TARGET).cpp -o $(TARGET).o -I $(HEADPATH)
$(CXX) -shared $(TARGET).o -o lib$(TARGET).so
rm $(TARGET).o
clean:
rm *.so
dynamic_library/test.cpp
#include<iostream>
#include "../include/test.h"
void CTestLib::func() {
printf("Hello, I am func\n");
}
test_dynamic_library/makefile
TARGET = main
#指定动态库路径和头文件的路径
LDFLAGS = -L ../dynamic_library/ -I ../include/
#指定在生成可执行文件时需要的动态库
LIBS = -ltest
CXX = g++
$(TARGET):
$(CXX) -o $(TARGET) $(TARGET).cpp $(LIBS) $(LDFLAGS)
clean:
rm $(TARGET)
test_dynamic_library/main.cpp
#include<iostream>
#include "../include/test.h"
int main()
{
CTestLib test;
test.func();
}
制作动态库
- 进入目录
dynamic_library
执行命令:
make
生成动态库文件libtest.so
,文件结构如下:
.
├── libtest.so
├── makefile
└── test.cpp
使用动态库
- 进入
test_dynamic_library
目录,执行命令:
make
生成可执行文件main
,文件目录变成:
.
├── main
├── main.cpp
└── makefile
- 然后执行main
./main
结果:
Hello, I am func
执行失败显示找不到动态库的解决方案:
终端执行命令:
#必须是绝对路径
LD_LIBRARY_PATH=/home/ubuntu/Dev/MyLib/dynamic_library/
export LD_LIBRARY_PATH
然后再执行make
命令。成功
可以通过
echo $LD_LIBRARY_PATH
查看LD_LIBRARY_PATH
变量的值。
补充知识
动态库的搜索路径:
- 1.编译目标代码时指定的动态库搜索路径;
- 2.环境变量
LD_LIBRARY_PATH
指定的动态库搜索路径; - 3.配置文件
/etc/ld.so.conf
中指定的动态库搜索路径; - 4.默认的动态库搜索路径
/lib
- 5.默认的动态库搜索路径
/usr/lib
。