问题

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

❯ 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.
  • 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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

解决

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

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

安装后重试,编译成功。

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

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

#include <stdio.h>

int main()
{
    void * ptr= nullptr;
    printf("%d\n",sizeof(ptr));
    return 0;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

更多说明

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

❯ getconf LONG_BIT
64
  • 1.
  • 2.

参考文章: 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