距离上次更新本文已经过去了 361 天,文章部分内容可能已经过时,请注意甄别

问题

如题,当我尝试在 wsl2 的 ubuntu 中使用 -m32 选项编译 32 位程序的时候,出现了下面的两种报错

plaintext
1
2
3
4
5
6
❯ g++ -m32 test.cpp -o test1 && ./test1
In file included from test.cpp:1:
/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory
27 | #include <bits/libc-header-start.h>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
plaintext
1
2
3
4
5
6
❯ g++ -m32 test.cpp -o test1 && ./test1
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/11/libstdc++.so when searching for -lstdc++
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/11/libstdc++.a when searching for -lstdc++
/usr/bin/ld: cannot find -lstdc++: No such file or directory
/usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/11/libstdc++.so when searching for -lstdc++
collect2: error: ld returned 1 exit status

解决

原因是当前缺少 32 位的开发库,需要安装

plaintext
1
sudo apt install gcc-multilib g++-multilib libc6-dev-i386 -y

安装后重试,编译成功。

plaintext
1
2
❯ g++ -m32  test.cpp -o test1 && ./test1
4

代码很简单,是一个打印指针大小的代码,在 32 位下指针大小是 4,64 位下指针大小是 8;

cpp
1
2
3
4
5
6
7
8
#include <stdio.h>

int main()
{
void * ptr= nullptr;
printf("%d\n",sizeof(ptr));
return 0;
}

更多说明

在 linux 下可以使用下面的命令查看你的系统位数。

plaintext
1
2
❯ getconf LONG_BIT
64

参考文章:assembly - /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/9/libstdc++.a when searching for -lstdc++ /usr/bin/ld: cannot find -lstdc++ - Stack Overflow