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

Windows下GCC编译C连接MySQL的链接错误及等效命令咨询

Windows下GCC编译对接MySQL的C代码解决方案

问题背景

我用C语言开发需要对接MySQL,Linux下编译只需两条简单命令:

gcc -g3 -Wall main.c $(mysql_config --libs) -o main.exe $(mysql_config --cflags)

或者更简化的:

gcc main.c -o main.exe -l mysqlclient

但在Windows 11下编译包含MySQL操作的C代码时遇到极大阻碍,全网搜遍方案都无效,现在急需这两条Linux命令的Windows等效版本,所有客户都用Windows系统,必须完成C与MySQL的集成。

尝试过的命令及错误

执行以下编译命令:

gcc -g3 -Wall main.o -o main.exe -L C:/'Program Files'/MySQL/'MySQL Server 8.0'/lib -lmysqlclient

得到错误输出:

c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: C:/Program Files/MySQL/MySQL Server 8.0/lib/mysqlclient.lib(libssl-3-x64.dll): Recognised but unhandled machine type (0x8664) in Import Library Format archive
main.o: In function `main':
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:40: undefined reference to `mysql_init@4'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:41: undefined reference to `mysql_real_connect@32'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:42: undefined reference to `mysql_errno@4'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:42: undefined reference to `mysql_error@4'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:43: undefined reference to `mysql_close@4'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:47: undefined reference to `mysql_close@4'
C:\Users\Ahmed Husein\Desktop\code\c_mysql_experiment/main.c:48: undefined reference to `mysql_server_end@0'
collect2.exe: error: ld returned 1 exit status

错误原因

  • 平台位数不匹配:使用32位MinGW编译,但安装的是64位MySQL,0x8664代表x86_64(64位)平台,32位MinGW无法处理64位库文件。
  • 库链接失败:平台不匹配导致库无法被正确识别,进而出现大量未定义引用错误。

解决方案

1. 统一平台位数

确保MinGW和MySQL版本位数一致:如果是64位MySQL,替换为MinGW-w64(64位版本的MinGW);如果坚持用32位MinGW,就安装32位版本的MySQL。

2. 等效编译命令

对应Linux第一条命令的Windows版本

找到MySQL安装目录下的mysql_config.exe(通常在C:\Program Files\MySQL\MySQL Server 8.0\bin),根据终端类型执行:

  • PowerShell:
gcc -g3 -Wall main.c -o main.exe `mysql_config --cflags` `mysql_config --libs`
  • CMD:
gcc -g3 -Wall main.c -o main.exe "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql_config.exe" --cflags "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql_config.exe" --libs

对应Linux第二条简化命令的Windows版本

Windows下MySQL的库名为libmysql.lib,需指定头文件目录和库目录:

gcc main.c -o main.exe -I "C:\Program Files\MySQL\MySQL Server 8.0\include" -L "C:\Program Files\MySQL\MySQL Server 8.0\lib" -lmysql

注:部分MySQL版本的库文件在lib\vs14目录下,需根据实际路径调整-L参数。

3. 额外注意事项

  • 如果分步骤编译,先执行编译生成目标文件:
gcc -c main.c -I "C:\Program Files\MySQL\MySQL Server 8.0\include"

再执行链接命令生成可执行文件。

  • 运行生成的main.exe时,需将MySQL目录下的libmysql.dll(位于C:\Program Files\MySQL\MySQL Server 8.0\lib)复制到exe所在目录,或者将MySQL的bin目录添加到系统PATH环境变量中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:03:11