如何在 64 位 GCC 的 C 和 C++ 中编译 32 位程序

2024 年 8 月 28 日 | 3 分钟阅读

企业办公室使用的系统涵盖了软件、能源以及食品饮料等领域。教育、IT或非IT行业都已从32位等旧版本转向64位版本。我们使用GCC或Clang等编译器来执行C或C++编程语言代码。不仅仅是转型,现代计算机的新产品其操作系统(无论是macOS还是Windows)的默认版本都是64位版本。

如果我们需要编译一个32位程序进行开发或测试,完成任务就会变得不可能或困难。尽管在我们的系统上安装64位环境非常有益,这有助于我们更快、更高效地完成任务,但运行32位程序并不切实际。因此,我们采用以下将要讨论的一些做法。

Linux命令(确认GCC的位环境版本)

在上述代码命令的第四行执行中,我们从系统得到确认,我们的位环境是64位本地。现在要开始执行我们的32位程序的本地64位版本,我们在Linux环境中的命令行中使用-m32应用以下代码命令,并且为了编译文件,我们使用-m32标志,例如文件jtp_intern.C

运行上述命令后,如果Linux环境编译器抛出以下错误:

致命错误:bits/prefs.h:在您的本地Linux Ubuntu环境中无法访问此类文件或目录

添加以下命令来安装GCC。上述错误表明GCC编译器缺失,它帮助我们运行和执行用C和C++编程语言编写的程序。

用于安装C++编程语言GCC的Linux命令

用于安装C编程语言GCC的Linux命令

C++ 代码

输出

Default 64-bit compilation, 
$ gcc -m32 test_c.c
test_c.c:4:28: warning: format '%lu' expects argument of type 'long unsigned
int,' but argument 2 has type 'unsigned int [-Wformat=]
printf("The Size is: %lu
", sizeof(long));
~~^
%u
Size = 8
The forced 32-bit compilation, 
$ gcc -m32 test_c.c
test_c.c: In function 'main':
test_c.c:4:28: warning: format '%lu' expects argument of type 'long unsigned
int,' but argument 2 has type 'unsigned int [-Wformat=]
printf("The Size is: %lu
", sizeof(long));
~~^
%u
Size = 4

C 代码

输出

Default 64-bit compilation, 
$ gcc -m32 test_c.c
test_c.c:3:1: warning: return type defaults to 'int' [-Wimplicit-int]
main(){
^~~~
test_c.c: In function 'main':
test_c.c:4:28: warning: format '%lu' expects argument of type 'long unsigned
int,' but argument 2 has type 'unsigned int [-Wformat=]
printf("The Size is: %lu
", sizeof(long));
~~^
%u
Size = 8
The forced 32-bit compilation, 
$ gcc -m32 test_c.c
test_c.c:3:1: warning: return type defaults to 'int' [-Wimplicit-int]
main(){
^~~~
test_c.c: In function 'main':
test_c.c:4:28: warning: format '%lu' expects argument of type 'long unsigned
int,' but argument 2 has type 'unsigned int [-Wformat=]
printf("The Size is: %lu
", sizeof(long));
~~^
%u
Size = 4