![](/img/trans.png)
[英]C++ program cross compile on linux using mingw works in msys2 but not directly in windows
[英]Compile C++ Windows exe standalone files with MSYS2
我最近開始使用 Msys2 安裝 gcc 編譯器來為 Windows 制作一些 exe。 它工作得很好,但是將我的 exe 傳遞給我的兄弟時出現了問題。 他的筆記本電腦沒有安裝 msys2,當他嘗試運行我的 exe 時會出現一些錯誤。 似乎很少需要 dll 文件才能使用我的 exe(如 msys-2.0.dll)。
我發現 msys2 使用這些文件來“偽造”機器上的操作系統,假裝它是 POSIX 操作系統。 有沒有辦法用 msys2 為 windows 編譯獨立的 exe? 我希望我的兄弟能夠在不安裝 msys 或其他的情況下使用我的 exe。
以下是所有細節,以更好地了解我的情況:
g++ HelloWord.cpp -o Helloword
是我用來編譯的那行C:\msys64\mingw64\bin
這里是存放g++的路徑 已修復:我僅使用 g++ 參數-static
解決了該問題。 是不是矯枉過正?
我的 MinGW 版本有點老了……
C:\example>where g++
C:\misc\mingw810_64\bin\g++.exe
C:\example>g++ --version
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
但同樣的想法:
C:\example>cat > compile_me.cpp
#include <iostream>
int main () { std::cout << "hi" << std::endl; }
^Z
C:\example>g++ compile_me.cpp -o compiled.exe
C:\example>compiled.exe
hi
C:\example>dumpbin /dependents compiled.exe
...
Image has the following dependencies:
KERNEL32.dll
msvcrt.dll
libstdc++-6.dll
...
在這種情況下(動態鏈接的標准庫),您將使用可執行文件部署 libstdc++6.dll,將其安裝到與 exe 相同的路徑(其他兩個通常存在於 windows 系統路徑中)。
如果要刪除該依賴項,請使用-static
:
C:\example>g++ compile_me.cpp -o compiled.exe -static
C:\example>compiled.exe
hi
C:\example>dumpbin /dependents compiled.exe
...
Image has the following dependencies:
KERNEL32.dll
msvcrt.dll
...
單獨部署 that.exe 應該沒問題。
文件大小會更大,但如今這並不是什么大不了的事。 此外,您的 MinGW / MSYS 安裝可能帶有條帶:
C:\example>dir compiled.exe
Volume in drive C is Windows
Volume Serial Number is D2BA-C6F0
Directory of C:\example
09/24/2022 06:49 PM 2,389,120 compiled.exe
1 File(s) 2,389,120 bytes
0 Dir(s) 135,945,314,304 bytes free
C:\example>strip compiled.exe
C:\example>dir compiled.exe
Volume in drive C is Windows
Volume Serial Number is D2BA-C6F0
Directory of C:\example
09/24/2022 07:03 PM 838,656 compiled.exe
1 File(s) 838,656 bytes
0 Dir(s) 135,944,765,440 bytes free
C:\example>compiled.exe
hi
如果您的特定可執行文件最終依賴於其他動態庫,並且供應商選擇不提供靜態鏈接的替代方案,那么您只需將它們與 exe 一起部署即可。 將所有內容放入 zip 文件或使用您最喜歡的可腳本化安裝程序通常很容易。
(注意:dumpbin 隨 Visual Studio 提供;並且可以在 VC\Tools 的 vs 安裝路徑中的某個適當子目錄中找到)。
MSYS2 編譯本機 PE32 可執行文件。 它不依賴於任何神奇的 msys 環境或 static 鏈接。
讓自己成為一個依賴漫游器,看看你的應用程序需要運行哪些 DLL。 不在 Windows 子目錄中的任何內容都應該是您關注的地方。 還要確保您的應用不需要任何特殊的 Microsoft 可再發行依賴項。
最終,您應該為您的應用程序創建一個安裝程序來處理依賴項。 我個人喜歡 Inno 設置,但還有很多其他的設置也很受歡迎。
OP 已經解決了他們的問題,但對於其他發現此問題的人來說:
mingw64.exe
或等效快捷方式啟動 MSYS2。which g++
以確保您使用的是/mingw64/bin/g++
。 如果它顯示一些其他g++
然后運行pacman -S mingw-w64-x86_64-toolchain
安裝工具鏈。g++
編譯您的代碼並使用-static
選項。ntldd yourprogram.exe
以檢查您的程序正在使用哪些 DLL,並確保它們是 Windows 的一部分,而不是 MSYS2 的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.