【C++从入门到放弃】C++编译生成动态链接库*.so及如何调用*.so进阶篇-编译jsoncpp

cstudy5中,我们演示了自己的写的源码进行编译成链接库,本章将讲解编译开源的jsoncpp

备注:上面提到的cstudy5示例参见: https://blog.csdn.net/hl_java/article/details/90812168

cppjson源码github

https://github.com/lzc-alioo/jsoncpp

git clone后发现文件太多,我把我们需要用到的复制到一个新项目中进行编译
复制include/json 、 src/lib_json/ 2个目录即可。

 tree
.
├── ReadMe.md
├── include
│   └── json
│       ├── allocator.h
│       ├── assertions.h
│       ├── autolink.h
│       ├── config.h
│       ├── features.h
│       ├── forwards.h
│       ├── json.h
│       ├── reader.h
│       ├── value.h
│       ├── version.h
│       └── writer.h
└── src
    ├── json_reader.cpp
    ├── json_tool.h
    ├── json_value.cpp
    ├── json_valueiterator.inl
    └── json_writer.cpp

3 directories, 17 files

编译链接库命令

 cd src
 g++  -std=c++11    json_reader.cpp  json_value.cpp  json_valueiterator.inl json_writer.cpp -I. -I../ -I../include  -I../include/json/   -fPIC -shared -o libjsoncpp2.so
ld: warning: ignoring file json_valueiterator.inl, file was built for unsupported file format ( 0x2F 0x2F 0x20 0x43 0x6F 0x70 0x79 0x72 0x69 0x67 0x68 0x74 0x20 0x32 0x30 0x30 ) which is not the architecture being linked (x86_64): json_valueiterator.inl

编译成功后,会在当前目录中产生一个新文件libjsoncpp2.so
备注:上面有warning提示,不用管,没有error的都可以编译成功

调用链接库

测试用例mainA.cpp源码清单

 more mainA.cpp
#include "json/json.h"
#include <iostream>

using namespace std;

int main() {

    const char *str = "{\"uploadid\": \"LZC000999\",\"code\": 100000,\"msg\": \"\",\"files\": \"\"}";

    cout << "llll:" << str << endl;

    Json::Reader reader;
    Json::Value root;
    if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素
    {
        std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"
        int code = root["code"].asInt();    // 访问节点,code = 100
        std::cout << "code:::::" << code << std::endl;

        string uploadid = root["uploadid"].asString();
        std::cout << "uploadid:::::" << uploadid << std::endl;
    }


    return 0;
}

生成可以执行程序

 g++  -std=c++11   mainA.cpp -L. -ljsoncpp2 ;
mainA.cpp:12:11: warning: 'Reader' is deprecated: Use CharReader and CharReaderBuilder instead [-Wdeprecated-declarations]
    Json::Reader reader;
          ^
/usr/local/include/json/reader.h:35:7: note: 'Reader' has been explicitly marked deprecated here
class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader {
      ^
/usr/local/include/json/config.h:124:58: note: expanded from macro 'JSONCPP_DEPRECATED'
#    define JSONCPP_DEPRECATED(message)  __attribute__ ((deprecated(message)))
                                                         ^
1 warning generated.

备注:上面只是告警,不用管

运行可执行程序

 ./a.out
llll:{"uploadid": "LZC000999","code": 100000,"msg": "","files": ""}
code:::::100000
uploadid:::::LZC000999

发布了100 篇原创文章 · 获赞 64 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/hl_java/article/details/91038464