# Windows 程序调试指南 ## 常见问题:Debug Assertion Failed ### 问题描述 运行编译后的程序时出现 "Debug Assertion Failed" 错误对话框。 ### 原因分析 1. **CRT 库冲突**:混合使用了调试版和发布版的 C 运行时库 2. **内存访问错误**:访问了无效内存或空指针 3. **初始化失败**:PHP 或 PHPX 未正确初始化 --- ## 🔧 解决方案 ### 方案 1:添加 /NODEFAULTLIB 选项(已实现) 编译器现在会自动添加以下链接选项来排除冲突的 CRT 库: ```cpp /NODEFAULTLIB:LIBCMT // 排除静态多线程 CRT /NODEFAULTLIB:LIBCMTD // 排除静态多线程调试 CRT /NODEFAULTLIB:MSVCRTD // 排除动态多线程调试 CRT ``` 这样可以确保只使用动态多线程 CRT(`/MD`),避免库冲突。 **重新编译:** ```powershell php bin/compiler.php examples/win32-hello/project.yml --no-console ``` --- ### 方案 2:使用 Visual Studio 调试器 #### 步骤 1:以调试模式编译 ```powershell # 启用调试信息 php bin/compiler.php examples/win32-hello/project.yml --debug-info --no-console ``` 这会在编译时添加 `/Zi` 选项,生成完整的调试符号。 #### 步骤 2:在 Visual Studio 中打开可执行文件 1. 打开 Visual Studio 2022 2. 菜单:**文件** → **打开** → **项目/解决方案** 3. 选择 `win32_hello.exe` 4. 或者直接将 exe 文件拖入 Visual Studio #### 步骤 3:设置断点 1. 在代码视图中找到您想调试的位置 2. 点击行号左侧的灰色区域,设置红色断点 3. 或者按 `F9` 在当前行设置断点 #### 步骤 4:启动调试 1. 按 `F5` 或点击 **调试** → **开始调试** 2. 程序会在断点处暂停 3. 可以查看变量值、调用堆栈等信息 #### 步骤 5:附加到正在运行的进程 如果程序已经启动但出现问题: 1. 在 Visual Studio 中:**调试** → **附加到进程** 2. 找到 `win32_hello.exe` 进程 3. 点击 **附加** 4. 程序会在下一个断点或异常处暂停 --- ### 方案 3:使用 WinDbg 调试 WinDbg 是 Windows SDK 中的强大调试工具。 #### 安装 WinDbg ```powershell # 通过 Microsoft Store 安装 winget install Microsoft.WinDbg ``` #### 使用方法 ```powershell # 启动 WinDbg 并加载程序 windbg .\win32_hello.exe # 或者附加到正在运行的进程 windbg -p ``` #### 常用命令 ``` g # 继续执行 (Go) k # 显示调用堆栈 (Stack trace) dv # 显示局部变量 !analyze -v # 详细分析崩溃原因 bp <地址> # 设置断点 ``` --- ### 方案 4:添加日志输出 由于 GUI 程序没有控制台,可以将调试信息写入日志文件: ```php getMessage()); debug_log("堆栈跟踪: " . $e->getTraceAsString()); } } ``` **查看日志:** ```powershell Get-Content .\debug.log -Wait ``` --- ### 方案 5:使用消息框调试 对于简单的调试,可以使用消息框显示变量值: ```php output.txt 2>&1` 3. 使用 ProcMon 监控 4. 检查 Windows 事件查看器 ### Q: 如何在没有 Visual Studio 的情况下调试? A: 1. 使用 WinDbg(免费) 2. 添加详细的日志输出 3. 使用消息框显示调试信息 4. 查看 Windows 事件日志 --- ## 📚 相关资源 - [Visual Studio 调试教程](https://docs.microsoft.com/visualstudio/debugger/) - [WinDbg 文档](https://docs.microsoft.com/windows-hardware/drivers/debugger/) - [CRT 库冲突解决方案](https://docs.microsoft.com/cpp/build/reference/nodefaultlib-ignore-library) - [Windows 调试技术](https://docs.microsoft.com/windows/win32/debug/) --- ## 🎯 快速修复步骤 如果遇到 "Debug Assertion Failed",按以下顺序尝试: 1. **重新编译**(使用最新的修复) ```powershell php bin/compiler.php examples/win32-hello/project.yml --no-console ``` 2. **清理构建目录** ```powershell Remove-Item -Recurse -Force build/ php bin/compiler.php examples/win32-hello/project.yml --no-console ``` 3. **添加调试信息重新编译** ```powershell php bin/compiler.php examples/win32-hello/project.yml --debug-info --no-console ``` 4. **使用 Visual Studio 调试** - 打开 exe 文件 - 按 F5 启动调试 - 查看输出窗口的错误信息 5. **添加日志输出** - 在关键位置添加 `debug_log()` 调用 - 查看日志文件定位问题 希望这些方法能帮助您成功调试程序!