linux下 g++如何编译生成动态库
时间: 2023-08-11 09:44:18 浏览: 95
在 Linux 下使用 g++ 编译生成动态库需要使用 -shared 选项。具体步骤如下:
1. 编写源代码文件,例如 test.cpp。
2. 使用 g++ 编译源代码文件,生成动态库文件。命令如下:
```
g++ -fPIC -shared -o libtest.so test.cpp
```
-fPIC 表示编译生成位置无关代码,-shared 表示生成动态库文件,-o 指定输出文件名为 libtest.so,test.cpp 是源代码文件名。
3. 编译成功后,会生成 libtest.so 文件,即为动态库文件。可以使用以下命令查看动态库信息:
```
$ file libtest.so
libtest.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=..., not stripped
```
可以看到,动态库文件类型为 ELF,是共享对象。
注意:动态库使用时需要使用 -l 指定库名进行链接,例如:
```
g++ main.cpp -L. -ltest -o main
```
其中,-L 指定库文件路径,-l 指定库名,main.cpp 是主程序代码文件,-o 指定输出文件名为 main。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)