Files
Knowledge/3 札记/MinGW-w64 工具链.md
T

78 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
**可以的**。MinGW-w64 在 Linux 下就是用来做这个的——它是一套**交叉编译工具链**,让你能在 Linux 上编译出直接调用 Windows SDK 接口的原生 Windows 程序。
---
## 🧠 工作原理
MinGW-w64 在 Linux 上运行时,本质是一个“翻译官”:
- 它**运行在 Linux 上**(宿主系统)
- 但包含了 **Windows 系统 API 的头文件和导入库**(`windows.h`、`kernel32.dll` 等)
- 生成的二进制文件是 **Windows PE 格式**(`.exe` / `.dll`),可以在 Windows 上直接运行
所以你在 Linux 下写的 `#include <windows.h>`、调用 `CreateFile()`、`MessageBox()` 等 Windows API,都能被正确编译和链接。
---
## 🔧 如何配置(你其实已经做过了)
你之前在 WSL 中编译 PQMagic 时已经安装了 MinGW-w64 工具链:
```bash
sudo apt install gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64
```
安装后,系统会提供以下编译器:
- `x86_64-w64-mingw32-gcc` —— 编译 64 位 Windows C 程序
- `x86_64-w64-mingw32-g++` —— 编译 64 位 Windows C++ 程序
这些编译器自带 Windows SDK 的头文件和库,所以你直接 `#include <windows.h>` 就能用。
---
## 📝 简单示例
创建一个 `hello_win.c`:
```c
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow) {
MessageBox(NULL, "Hello from Linux-cross-compiled Windows app!",
"MinGW Cross Compile", MB_OK);
return 0;
}
```
在 Linux 终端中编译:
```bash
x86_64-w64-mingw32-gcc -o hello.exe hello_win.c -lgdi32 -luser32
```
生成的 `hello.exe` 复制到 Windows 上双击就能运行,会弹出一个 Windows 消息框。
---
## ⚠️ 几点需要注意
### 1. 运行时依赖
MinGW 编译的程序依赖 MinGW 自己的运行时库(如 `libgcc_s_seh-1.dll`、`libstdc++-6.dll`)。如果要在没有安装 MinGW 的 Windows 上运行,需要把这些 DLL 一起打包,或者编译时静态链接:
```bash
x86_64-w64-mingw32-g++ -static-libgcc -static-libstdc++ -o myapp.exe myapp.cpp
```
### 2. 线程模型选择
安装时可能会让你选择 **posix** 还是 **win32** 线程模型:
- **posix**:使用 pthread 接口实现 `std::thread`,兼容性更好
- **win32**:使用 Windows 原生线程 API
如果依赖的第三方库(如 OpenCV)是用 posix 模型编译的,你的工具链也要选 posix。可以用 `update-alternatives` 切换。
### 3. 异常处理模型
64 位 Windows 推荐选 **seh**(结构化异常处理),性能更好。
### 4. 与 MSVC 的兼容性
MinGW 和 MSVC(Visual Studio 的编译器)使用不同的运行时库和名称修饰规则。如果要在 MSVC 项目中使用 MinGW 编译的 DLL,建议用 `extern "C"` 导出函数,避免 C++ 名称修饰带来的链接问题。