使用 C 和 C++ 在 64 位 gcc 上編譯 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
廣告