如何在 64 位 gcc 中編譯 C 和 C++ 的 32 位程式
現在編譯器帶有預設的 64 位版本。有時我們需要對程式碼進行編譯並將其執行到某個 32 位系統中。這時,我們必須使用此特性。
首先,我們必須檢查 gcc 編譯器的當前目標版本。要檢查此版本,我們必須鍵入此命令。
gcc –v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper OFFLOAD_TARGET_NAMES=nvptx-none OFFLOAD_TARGET_DEFAULT=1 Target: x86_64-linux-gnu ........... ........... ...........
此處顯示的目標為 x86_64。因此我們正在使用 64 位版本的 gcc。現在要使用 32 位系統,我們必須編寫以下命令。
gcc –m32 program_name.c
有時此命令可能會生成如下所示的錯誤。這表示 gcc 的標準庫缺失。在這種情況下,我們必須安裝它們。
In file included from test_c.c:1:0: /usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory #include <bits/libc-header-start.h> ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated.
現在,要安裝 gcc 的標準庫,我們必須編寫以下命令。
sudo apt-get install gcc-multilib sudo apt-get install g++-multilib
現在透過使用此程式碼,我們將看到在 32 位和 64 位系統中執行程式碼的區別。
示例
#include<stdio.h> main(){ printf("The Size is: %lu\n", sizeof(long)); }
輸出
$ gcc test_c.c test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){ ^~~~ $ ./a.out The Size is: 8
輸出
$ 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\n", sizeof(long)); ~~^ %u $ ./a.out The Size is: 4
廣告