VS Code用MinGW64编译C++代码安装MSYS2软件并配置SQLite3库和测试引用库代码的完整具体步骤。
1. 安装 MSYS2
- 下载安装包:
- 访问 MSYS2 官网
- 下载
msys2-x86_64-xxxx.exe
(最新版)
- 安装:
- 运行安装程序,按提示操作(默认路径
C:\msys64
)
- 运行安装程序,按提示操作(默认路径
- 更新包数据库 :
-
打开 MSYS2 MSYS(开始菜单中)
-
执行:
bashpacman -Syu
-
关闭终端,重新打开 MSYS2 MSYS ,再次执行:
bashpacman -Su
-
2. 安装 MinGW64 工具链和 SQLite3
-
打开 MSYS2 MinGW x64 终端(非 MSYS 终端!)
-
安装编译器和 SQLite3:
bashpacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-sqlite3
3. 配置 VS Code
(1) 设置环境变量
- 将 MinGW64 的
bin
目录添加到系统PATH
:- 路径示例:
C:\msys64\mingw64\bin
- 操作步骤 :
- Win + S 搜索 "环境变量" → 编辑系统环境变量
- 在
Path
中添加C:\msys64\mingw64\bin
- 路径示例:
(2) 安装 VS Code 扩展
- 安装官方扩展:C/C++
4. 配置 VS Code 项目
(1) 创建项目结构
your_project/
├── .vscode/
│ ├── tasks.json (编译配置)
│ └── c_cpp_properties.json (IntelliSense 配置)
├── main.cpp (测试代码)
└── Makefile (可选)
(2) 配置 c_cpp_properties.json
json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"C:/msys64/mingw64/include/**" // SQLite3 头文件路径
],
"compilerPath": "C:/msys64/mingw64/bin/g++.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
(3) 配置 tasks.json
(编译任务)
json
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "Build with SQLite3",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.exe",
"-I", "C:/msys64/mingw64/include", // 头文件路径
"-L", "C:/msys64/mingw64/lib", // 库文件路径
"-lsqlite3" // 链接 SQLite3
],
"options": {
"cwd": "C:/msys64/mingw64/bin" // 确保运行时能找到 DLL
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
5. 测试代码
(1) 创建 main.cpp
cpp
#include <iostream>
#include <sqlite3.h>
int main() {
// 测试 SQLite3 版本
std::cout << "SQLite Version: " << sqlite3_libversion() << std::endl;
// 测试数据库连接
sqlite3 *db;
int rc = sqlite3_open(":memory:", &db);
if (rc == SQLITE_OK) {
std::cout << "Database opened successfully!" << std::endl;
sqlite3_close(db);
} else {
std::cerr << "Error opening database: " << sqlite3_errmsg(db) << std::endl;
}
return 0;
}
(2) 编译运行
- 在 VS Code 中打开
main.cpp
- 编译 :按
Ctrl+Shift+B
执行编译任务 - 运行 :
-
在终端中执行:
bash./main.exe
-
或使用 VS Code 调试功能(按
F5
)
-
6. 验证输出
成功时输出:
SQLite Version: 3.xx.x
Database opened successfully!
常见问题解决
-
找不到
sqlite3.h
:- 检查
c_cpp_properties.json
中的includePath
是否指向C:/msys64/mingw64/include
- 检查
-
链接失败(undefined reference):
- 确保
tasks.json
中已添加-L C:/msys64/mingw64/lib -lsqlite3
- 确保
-
运行时缺少
sqlite3.dll
:- 将
C:\msys64\mingw64\bin\sqlite3.dll
复制到项目目录 - 或永久添加
C:\msys64\mingw64\bin
到系统PATH
- 将
-
MSYS2 更新后路径变化:
- 所有配置中的路径保持
C:/msys64/...
(使用正斜杠)
- 所有配置中的路径保持
关键提示 :始终使用 MSYS2 MinGW x64 终端安装库,并在 VS Code 中配置正确的 MinGW64 路径(
C:/msys64/mingw64
)。