linux动态库的构建---借助cjson库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/localhostcom/article/details/79491464

  环境:ubuntu

    json库很简单只有一个.c文件和.h头文件,把它封装为动态库,方便给其它程序调用;特别注意的一点是:当静态库和动态库同名时, gcc命令将优先使用动态库。

    下面就以cJSON库为例:

1.动态库编译

    ubuntu$ sudo gcc -shared -fPIC  -o libjson.so cJSON.c -I. -lm -ldl

    -fPIC :表示代码是和地址无关的,不需要被不同的模块重定位。

    -ldl   :是显式加载动态库的动态函数库。

    /* 注意:库需要的链接库,编译时候一定要带上。以上一条命令轻轻松松搞定 */

2.使用接口

/**********************************************
 *	@Filename		: test.c
 *	@Description	: use json api	
 *	@date			:2018-03-09 23:10
 **********************************************/
#include <stdio.h>
#include "cJSON.h"
#include <stdlib.h>
#include <string.h>

int main(void)
{
	cJSON* root = cJSON_CreateObject();
	cJSON_AddStringToObject(root,"name","tobiubiu");	//string
	cJSON_AddNumberToObject(root,"year",18);		//int 
	
	char *data = cJSON_PrintUnformatted(root);

	printf("--- data : %s ---\n",data);
	cJSON_Delete(root);	//free
	root = NULL;
	return 0;
}

3.遇到问题

    如果执行程序或编译过程出现查找不到某些库,方法之一是:将库的路径加载到:

         #sudo vim /etc/ld.so.conf

     然后执行重新读取:

        #ldconfig

4.图示结果


猜你喜欢

转载自blog.csdn.net/localhostcom/article/details/79491464