VS Code配置MinGW64编译libxlsxwriter和xlsxio库
VS Code用MinGW64编译C++代码安装MSYS2软件并配置libxlsxwriter和xlsxio库和测试引用库代码的完整具体步骤。
1. 安装 MSYS2
- 下载安装包:
- 官网:https://www.msys2.org/
- 选择
x86_64
版本下载
- 安装:
- 运行安装程序,默认路径
C:\msys64
- 勾选
Run MSYS2 now
完成初始化
- 运行安装程序,默认路径
- 更新基础包(在打开的 MSYS2 终端中执行):
pacman -Syu # 关闭窗口后重新打开终端 pacman -Su
2. 安装 MinGW64 工具链
在 MSYS2 终端中执行:
pacman -S --needed mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake mingw-w64-x86_64-make
3. 安装依赖库
(1) 安装 libxlsxwriter(写 Excel 文件)
pacman -S mingw-w64-x86_64-libxlsxwriter
(2) 安装 xlsxio(读 Excel 文件,替代 xlsxreader)
# 安装依赖
pacman -S mingw-w64-x86_64-expat mingw-w64-x86_64-minizip# 克隆源码
git clone https://github.com/brechtsanders/xlsxio.git
cd xlsxio# 编译安装
mkdir build && cd build
cmake -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=/mingw64 ..
make install
4. 配置 VS Code
(1) 设置环境变量
- 将 MinGW64 加入系统
PATH
:C:\msys64\mingw64\bin
- 重启 VS Code 使配置生效。
(2) 安装扩展
- C/C++ (Microsoft)
- CMake Tools (可选)
(3) 配置 c_cpp_properties.json
- 按
Ctrl+Shift+P
>C/C++: Edit Configurations (UI)
- 添加包含路径:
"includePath": ["${workspaceFolder}/**","C:/msys64/mingw64/include","C:/msys64/mingw64/include/xlsxio" ],
- 添加库路径:
"compilerPath": "C:/msys64/mingw64/bin/g++.exe"
(4) 配置 tasks.json
- 创建
.vscode/tasks.json
: - 写入:
{"version": "2.0.0","tasks": [{"label": "build","type": "shell","command": "g++","args": ["-g", "-std=c++11","${file}","-o", "${fileDirname}/${fileBasenameNoExtension}.exe","-I", "C:/msys64/mingw64/include","-L", "C:/msys64/mingw64/lib","-lxlsxwriter", "-lxlsxio_read"],"group": { "kind": "build", "isDefault": true },"problemMatcher": ["$gcc"]}]
}
5. 测试代码
(1) 写入 Excel 测试(libxlsxwriter)
创建 write_example.cpp
:
#include "xlsxwriter.h"
int main() {lxw_workbook *wb = workbook_new("test.xlsx");lxw_worksheet *ws = workbook_add_worksheet(wb, NULL);worksheet_write_string(ws, 0, 0, "Hello", NULL);worksheet_write_number(ws, 1, 0, 123.45, NULL);return workbook_close(wb);
}
(2) 读取 Excel 测试(xlsxio)
创建 read_example.cpp
:
#include <xlsxio_read.h>
#include <iostream>
int main() {xlsxioreader xlsxioread = xlsxioread_open("test.xlsx");if (xlsxioread) {xlsxioreadersheet sheet = xlsxioread_sheet_open(xlsxioread, NULL, XLSXIOREAD_SKIP_EMPTY_ROWS);if (sheet) {char* value;while (xlsxioread_sheet_next_row(sheet)) {while ((value = xlsxioread_sheet_next_cell(sheet)) != NULL) {std::cout << value << "\t";free(value);}std::cout << std::endl;}xlsxioread_sheet_close(sheet);}xlsxioread_close(xlsxioread);}return 0;
}
6. 编译运行
- 编译写入程序:
- 打开
write_example.cpp
- 按
Ctrl+Shift+B
编译 - 终端执行生成的文件:
./write_example.exe
- 打开
- 编译读取程序:
- 打开
read_example.cpp
- 按
Ctrl+Shift+B
编译 - 终端执行:
./read_example.exe
- 打开
常见问题解决
- 库链接失败:
- 检查
tasks.json
中的-L
路径是否正确 - 确认库文件存在:
C:/msys64/mingw64/lib/libxlsxwriter.a
和libxlsxio_read.a
- 检查
- 头文件缺失:
- 在
c_cpp_properties.json
中检查includePath
- 在
- MSYS2 更新问题:
- 定期运行
pacman -Syu
更新包
- 定期运行
注意:
xlsxreader
库已由xlsxio
替代(提供读写支持)。如需其他库,可通过pacman -Ss 库名
搜索 MSYS2 仓库。