使用JsonCPP解析API请求编译失败,出现LNK2019链接错误
我编写了以下C++代码,计划调用CoinGecko的API获取比特币价格数据,并使用JsonCPP解析响应后输出格式为{"Bitcoin" {"USD: 23000"}}的结果:
#include<string> #include<iostream> #include<json/json.h> #include<cpr/cpr.h> using namespace std; using namespace cpr; int main() { Response r = Get(Url{ "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" }); Json::Value data; Json::Reader reader; reader.parse(r.text, data); cout << data << endl; }
当直接输出响应文本r.text时程序可正常运行,但使用JsonCPP解析时,编译提示「存在构建错误,是否运行之前的构建版本?」,具体构建错误信息如下:
Build started... 1>------ Build started: Project: Project 1,
Configuration: Debug x64 ------ 1>Main.obj : error LNK2019: unresolved
external symbol "public: __cdecl Json::Value::Value(enum
Json::ValueType)" (??0Value@Json@@QEAA@W4ValueType@1@@Z) referenced in
function main 1>Main.obj : error LNK2019: unresolved external symbol
"public: __cdecl Json::Value::~Value(void)" (??1Value@Json@@QEAA@XZ)
referenced in function main 1>Main.obj : error LNK2019: unresolved
external symbol "public: __cdecl Json::Reader::Reader(void)"
(??0Reader@Json@@QEAA@XZ) referenced in function main 1>Main.obj :
error LNK2019: unresolved external symbol "public: bool __cdecl
Json::Reader::parse(class std::basic_string<char,struct
std::char_traits,class std::allocator > const &,class
Json::Value &,bool)"
(?parse@Reader@Json@@QEAA_NAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AEAVValue@2@_N@Z)
referenced in function main 1>Main.obj : error LNK2019: unresolved
external symbol "class std::basic_ostream<char,struct
std::char_traits > & __cdecl Json::operator<<(class
std::basic_ostream<char,struct std::char_traits > &,class
Json::Value const &)"
(??6Json@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV12@AEBVValue@0@@Z)
referenced in function main
这些LNK2019错误是典型的链接器找不到JsonCPP库文件导致的——编译器能识别头文件,但链接阶段无法定位实现代码。按以下步骤修复:
确认库文件存在:确保已编译JsonCPP,生成对应模式的库文件:
- Debug模式:
jsoncppd.lib(Windows)/libjsoncppd.a(Linux/macOS) - Release模式:
jsoncpp.lib(Windows)/libjsoncpp.a(Linux/macOS)
- Debug模式:
配置链接器路径(Visual Studio):
- 右键项目 → 属性 → 链接器 → 常规 → 附加库目录:添加JsonCPP库文件所在文件夹路径
- 链接器 → 输入 → 附加依赖项:添加对应模式的库文件名(比如Debug加
jsoncppd.lib)
匹配编译模式:项目的Debug/Release模式、x86/x64架构必须和JsonCPP库的编译参数完全一致,不能交叉混用。
CMake项目简化配置:如果用CMake构建,直接添加以下配置自动处理依赖:
cmake_minimum_required(VERSION 3.10) project(BitcoinPrice) find_package(JsonCpp REQUIRED) find_package(cpr REQUIRED) add_executable(BitcoinPrice main.cpp) target_link_libraries(BitcoinPrice PRIVATE JsonCpp::JsonCpp cpr::cpr)
代码优化(匹配预期输出格式)
原代码输出的Json格式和要求的{"Bitcoin" {"USD: 23000"}}不符,修改后代码如下:
#include<string> #include<iostream> #include<json/json.h> #include<cpr/cpr.h> using namespace std; using namespace cpr; int main() { Response r = Get(Url{ "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" }); Json::Value data; Json::Reader reader; reader.parse(r.text, data); cout << "{\"Bitcoin\": {\"USD: " << data["bitcoin"]["usd"].asInt() << "\"}}" << endl; return 0; }
内容的提问来源于stack exchange,提问作者John Doe

