Clang++编译成功但可执行文件无法正常运行问题求助
问题:Clang编译含std::stack的程序运行崩溃,G编译正常
我编写了一段检查括号表达式合法性的C++代码(输入{()}[{()}]返回true,()(}返回false),代码如下:
// program to check if parentheses expression is correct // {()}[{()}] = true, ()(} = false #include <string.h> #include <iostream> #include <stack> using namespace std; int par(string str) { int a = str.length(); stack<char> S; char x; for (int i = 0; i < a; i++) { x = str[i]; if (x == '(' || x == '[' || x == '{') { S.push(x); } else { if (x == ')') { if (S.top() == '(') { S.pop(); } else return 0; } else if (x == ']') { if (S.top() == '[') { S.pop(); } else return 0; } else if (x == '}') { if (S.top() == '{') { S.pop(); } else return 0; } } } if (!S.empty()) { return 0; } else return 1; } int main() { int n; string str; cin >> n; for (int i = 0; i < n; i++) { cin >> str; cout << par(str) << endl; } return 0; }
编译与运行情况
- 使用命令
clang++ -std=c++20 -Wall -Wextra -pedantic -g par.cpp -o par.exe编译成功,但直接打开par.exe时程序立即终止。 - 使用命令
g++ -std=c++20 -Wall -Wextra -pedantic -g par.cpp -o par.exe编译后,程序运行完全正常。
编译器版本
- Clang++版本:
>clang++ --version clang version 15.0.5 Target: x86_64-w64-windows-gnu Thread model: posix InstalledDir: C:/msys64/ucrt64/bin
- G++版本:
>g++ --version g++.exe (tdm64-1) 10.3.0 Copyright (C) 2020 Free Software Foundation, Inc.
我怀疑问题和<stack>/<queue>库有关,因为不含这些库的代码用Clang++编译后运行正常,求解决思路。
可能的解决方向
1. 用MSYS2终端运行程序
MSYS2 UCRT64环境下的Clang编译的程序,依赖UCRT运行时库和MSYS2提供的标准库,直接双击exe可能找不到动态库导致崩溃。
- 解决方式:打开MSYS2的UCRT64终端,在终端内执行
./par.exe,终端会自动配置环境变量让程序找到所需依赖。
2. 尝试静态编译
如果需要双击运行程序,可以用静态编译把依赖库打包进exe:
clang++ -std=c++20 -Wall -Wextra -pedantic -g par.cpp -o par.exe -static
注:静态编译会增大exe体积,部分库可能不支持静态链接,需根据实际情况调整。
3. 修复代码中的未定义行为
你的代码存在隐患:遇到右括号时直接调用S.top(),但未检查栈是否为空(比如输入")"时栈为空),这属于未定义行为,Clang和G++对这类行为的处理可能不同。
- 修复代码:在调用
S.top()前先判断栈是否为空:
else { if (S.empty()) return 0; // 新增:处理空栈遇到右括号的情况 if (x == ')') { if (S.top() == '(') { S.pop(); } else return 0; } // 其余右括号判断分支同理,先检查栈是否为空 }
这虽然不一定是当前崩溃的直接原因,但能避免更多潜在问题,提升程序在Clang下的稳定性。
4. 更新MSYS2环境
确保MSYS2 UCRT64环境是最新状态,运行以下命令更新所有包:
pacman -Syu
更新后重新编译代码,可能解决库版本不兼容的问题。
内容的提问来源于stack exchange,提问作者Trung Kiến
相关产品推荐
相关产品推荐

