近期因為項目需要,簡化流程,寫了一些 Matlab 程序,並配備上了 GUI 界面使其簡單易用。然后問題來了,可移植性。使用 Matlab 生成 EXE 文件(可以封裝很多的 function),然后在一台安裝有 Matlab Runtime 環境的電腦上運行,是一種不錯的選擇。
本文主要就我自己在 GUI 生成 EXE 文件上遇到的一些問題以及解決辦法進行一個說明,希望可以幫助到有同樣需求的人。
配置環境
- Windows 10系統
- Matlab 2013a
- Visual Studio 2013
配置方法
打開 Matlab,在命令行中輸入
mbuild -setup
進行編譯環境的配置,將會出現如下的界面。
Welcome to mbuild -setup. This utility will help you set up
a default compiler. For a list of supported compilers, see
http://www.mathworks.com/support/compilers/R2013a/win64.html
Please choose your compiler for building shared libraries or COM components:
Would you like mbuild to locate installed compilers [y]/n?
輸入 y
確認后觀察是否有編譯器的存在,我的一開始是沒有的,如果你的有 matlab 自帶的 lcc,那么幸運的是,你不用麻煩安裝別的編譯器了,這個已經足夠,可以搜索與之相關的文章了;不幸的是后面的可能就不適合你了,因為我最后是使用的 VS 的編譯器環境。
如果你也沒有任何的編譯器,那么很好,可以接着和我操作了,輸入 Ctrl + C
退出當前命令,然后重新輸入 mbuild -setup
。選擇 n
,可以看到,出現了如下的一些選項。
Select a compiler:
[1] Microsoft Software Development Kit (SDK) 7.1
[2] Microsoft Visual C++ 2008 SP1
[3] Microsoft Visual C++ 2010
[4] Microsoft Visual C++ 2012
[0] None
Matlab 2013a 中居然沒有我安裝的VS2013,傷心。不過想來也是,沒有是正常的,那么后續怎么辦呢,按照其中的安裝唄,2008SP1,2010, 2012 都可以。博主在這里選擇了 VS2010,同一個電腦是可以安裝不同版本的 VS 哦。
在 VS2010 完成后,重新啟動 Matlab,然后再次輸入這條指令 mbuild -setup
,但是這次我們選擇 y
,進入如下的界面,這次就可以看到我們安裝的 VS2010 環境了,Nice!然后一路正常設置就好。
Would you like mbuild to locate installed compilers [y]/n? y
Select a compiler:
[1] Microsoft Visual C++ 2010 in D:\Program Files (x86)\Microsoft Visual Studio 10.0
[0] None
Compiler: 1
Please verify your choices:
Compiler: Microsoft Visual C++ 2010
Location: D:\Program Files (x86)\Microsoft Visual Studio 10.0
Are these correct [y]/n? y
****************************************************************************
Warning: Applications/components generated using Microsoft Visual C++
2010 require that the Microsoft Visual Studio 2010 run-time
libraries be available on the computer used for deployment.
To redistribute your applications/components, be sure that the
deployment machine has these run-time libraries.
****************************************************************************
Trying to update options file: C:\Users\AirBird\AppData\Roaming\MathWorks\MATLAB\R2013a\compopts.bat
From template: D:\Program Files\MATLAB\R2013a\bin\win64\mbuildopts\msvc100compp.bat
Done . . .
至此,Matlab 編譯器配置完成。
生成EXE文件
在命令行中鍵入如下命令可以進行 EXE 文件的生成。
mcc -m myfile.m; % 只有 .m 文件時
mcc -m myfile.fig myfile.m; % .fig 文件和 .m 文件一起時
但是,在運行生成的 EXE 文件時我們會發現有黑框的存在,這個黑框其實是作為控制台的存在,有什么信息可以打印到上面。但是很多時候我們在運行的時候不希望黑框的生成,那么該如何操作呢?這里只需要更改下命令就可以了,如下。
mcc -e myfile.m; % 只有 .m 文件時
mcc -e myfile.fig myfile.m; % .fig 文件和 .m 文件一起時
其中 -e
是生成不帶黑框的 EXE 程序,是不是很神奇。但是這里需要注意的是,-e
的用法只適合 VS 的引擎。有關 mcc 的用法,可以 help mcc
或者 doc mcc
進行查閱。本文摘抄部分信息如下。
e Macro that generates a C Windows application on the Windows platform. On
non-Windows platforms, it is the same as the macro -m. This is
equivalent to the options "-W WinMain -T link:exe", which can be found
in the file <MATLAB>/toolbox/compiler/bundles/macro_option_e.