You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MySQL X DevAPI连接MySQL时出现未定义引用错误求助

使用MySQL X DevAPI连接C++与MySQL时的未定义引用错误解决

编译代码时出现以下未定义引用错误:

undefined reference to `mysqlx::abi2::r0::common::Settings_impl::Data::init_connection_attr()'
undefined reference to `mysqlx::abi2::r0::string::Impl::from_utf8(mysqlx::abi2::r0::string&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
undefined reference to `mysqlx::abi2::r0::string::Impl::to_utf8[abi:cxx11](mysqlx::abi2::r0::string const&)'
undefined reference to `mysqlx::abi2::r0::common::Value::print(std::ostream&) const'
undefined reference to `mysqlx::abi2::r0::internal::Result_detail::Result_detail(mysqlx::abi2::r0::common::Result_init&)'
undefined reference to `mysqlx::abi2::r0::internal::Doc_result_detail::get_doc()'

我的代码:

#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include "C:/Program Files/MySQL/MySQL Server 8.3/include/mysql.h"
#include "mysqlx/xdevapi.h"

int main() {
    std::cout << "Connecting to MySQL server..." << std::endl;

    try {
        mysqlx::Session sess("localhost", 33060, "root", "root");
        mysqlx::Schema db = sess.getSchema("test");

        mysqlx::Collection myColl = db.getCollection("my_collection");

        mysqlx::DocResult myDocs = myColl.find("name like :param")
                                         .limit(1)
                                         .bind("param", "L%")
                                         .execute();

        std::cout << myDocs.fetchOne() << std::endl;
    } catch (const mysqlx::Error &e) {
        std::cout << "MySQL X DevAPI Exception: " << e.what() << std::endl;
    }

    return 0;
}

编译命令:

g++ -std=c++20 -o test_sql test_sql.cpp -I"C:/MySQL/MySQL Connector C++ 8.3/include" -L"C:/MySQL/MySQL Connector C++ 8.3/lib64/vs14" -lmysqlcppconn8

解决方法:

  1. 替换兼容的库文件
    你用GCC(g++)编译,但指定的库路径是VS14(MSVC)编译的库,两者ABI完全不兼容,必须下载MinGW版本的MySQL Connector C++,将库路径替换为MinGW对应的目录(比如lib64/mingw)。

  2. 链接正确的X DevAPI库
    确保编译时链接支持X DevAPI的库,MinGW版本下对应库文件是libmysqlcppconn8.dll.a,编译命令中保留-lmysqlcppconn8即可,但要指向正确的MinGW库目录。

  3. 清理冗余头文件
    代码中包含的mysql.h是MySQL传统C API的头文件,与X DevAPI无关,建议删除,避免潜在编译冲突。

  4. 确保头文件与库版本匹配
    确认include目录下的头文件(尤其是mysqlx/下的文件)与链接的库版本完全一致(均为8.3),版本不匹配会导致ABI不一致,触发未定义引用错误。

  5. 调整后的编译命令示例
    假设MinGW版本的库路径为C:/MySQL/MySQL Connector C++ 8.3/lib64/mingw,编译命令改为:

    g++ -std=c++20 -o test_sql test_sql.cpp -I"C:/MySQL/MySQL Connector C++ 8.3/include" -L"C:/MySQL/MySQL Connector C++ 8.3/lib64/mingw" -lmysqlcppconn8
    

内容的提问来源于stack exchange,提问作者the_big_blackbox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:52:31