gcc/g++ 动态 静态 链接库 so

本文介绍了一个使用C++编写的简单mysql类,并详细展示了如何将其拆分为多个源文件进行编译,最终生成动态链接库及可执行文件的过程。文章涵盖了头文件定义、成员函数实现、主函数调用及动态库的编译命令等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明:

文件目录:my

文件: foo.h num.cpp size.cpp name.cpp main.cpp

准备文件:

foo.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef _MY_FOO_H
#define _MY_FOO_H
 
#define u_int unsigned int
#include<malloc.h>
class  mysql
{
 
     public  :
         char  *file_name;
         u_int file_size;
         int  num; 
     public  :
         void  init_size(u_int size);
         u_int get_size();
         char  *get_name();
         void  init_name( char * name);
         void  init_num( int  n);
         int  get_num();
         void  add( int  n);
         void  del( int  n);
         ~mysql()
         {
             free (file_name);
         }
};

num.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include"foo.h"
#include<iostream>
using  namespace  std;
 
void  mysql::init_num( int  n)
{
     this ->num = n;
}
 
int  mysql::get_num()
{
     return  this ->num;
}

size.cpp

1
2
3
4
5
6
7
8
9
10
11
#include"foo.h"
 
void  mysql::init_size(u_int size) 
{
     this ->file_size = size;
}
 
u_int mysql::get_size()
{
     return  this ->file_size;
}

name.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include"foo.h"
#include<stdio.h>
#include<string.h>
#include<malloc.h>
 
void  mysql::init_name( char  * name) 
{
     if ( (  sizeof (name) + 1 ) >  this ->file_size) 
     {
         printf ( "the length of name is too long\n" );
         return  ;
     }
     this ->file_name = ( char  *) calloc (1, sizeof (name)+1);
     strcpy ( this ->file_name, name);
}
 
char * mysql::get_name()
{
     return  this ->file_name;
}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include"foo.h"
#include<iostream>
using  namespace  std;
int  main()
{
     mysql *my =  new  mysql();
     my->init_num(4);
     int  num = my->get_num();
     cout <<  "num is "  << num << endl;
     my->init_size(100);
     u_int size = my->get_size();
     cout <<  "file_size is "  << size << endl;
     my->init_name( ( char *)( "MYSQL" ) );
     cout << my->get_name() << endl;
     return  0; 
}

编译生成so文件:

1
2
3
4
5
6
7
libnum.so
$ g++ num.cpp -fPIC -shared -o libnum.so
libsize.so
$ g++ size.cpp -fPIC -shared -o libsize.so
libname.so
$ g++ name.cpp -fPIC -shared -o libname.so
$ ls


说明

-fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的。  

-L.:表示要连接的库在当前目录中  

-lxxx:编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名称libxxx.so 

 

生成可执行文件

$ g++ main.cpp -L. -lnum -lname -lsize -o main然后就有可执行文件,但是好像不给力,没法运行。因为没有修改,LD_LIBRARY_PATH,这个环境变量指示动态连接器可以装载动态库的路径。


加上 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.  然后执行ldd

然后运行./main,终于出现结果了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值