macOS 12.6(M1 MacBook Air)Linker编译断言失败问题求助
问题场景
- 设备:M1芯片MacBook Air
- 系统:macOS 12.6
- 编译命令:
g++ file.cpp - 编译代码:
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<vector<int>> v(n, vector<int>(2)); cout<<2<<"\n"; return 0; }
- 错误信息:
0 0x1022a41a0 __assert_rtn + 140
1 0x10212ba8c mach_o::relocatable::Parser::parse(mach_o::relocatable::ParserOptions const&) + 4536
2 0x1020fdd38 mach_o::relocatable::Parser::parse(unsigned char const*, unsigned long long, char const*, long, ld::File::Ordinal, mach_o::relocatable::ParserOptions const&) + 148
3 0x1021664ac ld::tool::InputFiles::makeFile(Options::FileInfo const&, bool) + 1468
4 0x102169360 ___ZN2ld4tool10InputFilesC2ER7Options_block_invoke + 56
5 0x1c17b41f4 _dispatch_client_callout2 + 20
6 0x1c17c8f8c _dispatch_apply_invoke_and_wait + 224
7 0x1c17c826c _dispatch_apply_with_attr_f + 1152
8 0x1c17c847c dispatch_apply + 108
9 0x1021691f4 ld::tool::InputFiles::InputFiles(Options&) + 616
10 0x1020eb6c0 main + 552
A linker snapshot was created at:
/tmp/a.out-2022-09-19-011653.ld-snapshot
ld: Assertion failed: (_file->_atomsArrayCount == computedAtomCount && "more atoms allocated than expected"), function parse, file macho_relocatable_file.cpp, line 2061.
collect2: error: ld returned 1 exit status
解决方法
- 指定C++标准版本编译:该错误多因默认编译标准与M1架构链接器兼容性冲突,添加标准参数强制使用C++11及以上版本即可:
可根据需求替换为g++ -std=c++17 file.cpp-std=c++11/-std=c++14/-std=c++20。 - 改用clang++编译:M1 macOS上的
g++实际是clang的别名,直接调用clang++可规避部分兼容性问题:
同样可搭配标准参数使用,如clang++ file.cppclang++ -std=c++17 file.cpp。 - 更新Xcode命令行工具:执行以下命令安装或重置工具链,修复架构相关的链接器bug:
xcode-select --install # 若已安装,执行重置路径 sudo xcode-select --reset - 清理编译缓存:删除临时生成的可执行文件和链接器快照,避免缓存异常导致的问题:
rm -f a.out /tmp/a.out-*.ld-snapshot
内容的提问来源于stack exchange,提问作者Omhari

