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