天天看點

使用MATLAB的MCC指令生成C/C++程式 C++錯誤知識

2015 0201 錯誤 困擾

解決方法:在連接配接器中添加 UnipolarSingle.lib

使用MATLAB的MCC指令生成C/C++程式 C++錯誤知識

http://blog.csdn.net/ithzhang/article/category/1120011

來源:http://www.360doc.com/content/12/0111/16/5864603_178760432.shtml

首先,配置MATLAB

用如下指令:

mex –setup

mbuild -setup

例一:将m檔案轉化成庫檔案使用

1、建立一個名為ceshidll.m的M函數檔案,該函數的功能是輸入兩組數完成兩組資料的插值拟合,并将結果用圖形表示:

ceshidll.m檔案内容如下:

function ceshidll(x,y)

a=min(x):0.1:max(x);

b = interp1(x,y,a,''spline'');%一維插值函數

plot(x,y,''*'',a,b);

2、在MATLAB Command中用如下指令編譯函數ceshidll.m:

>> mcc -t -W libhg:dlltest -T link:lib -h libmmfile.mlib ceshidll.m

參數說明:

-t 将m檔案編譯為C\C++代碼

-W libhg:dlltest 生成使用C函數圖形庫的檔案,生成的檔案名為dlltest

-T link:lib 生成庫檔案

-h 輔助選項,可以将任何被調用的輔助函數都包含到編譯的檔案中

libmmfile.mlib連接配接任何需要的共享函數庫

ceshidll.m 被編譯的檔案名

編譯完成後在MATLAB目前目錄下會生成以下檔案: ceshidll.c、ceshidll.h 、dlltest.c 、dlltest.exports、dlltest.h、dlltest.mlib、dlltest.exp、dlltest.lib、dlltest.dll。其中dlltest.h 、dlltest.lib和dlltest.dll檔案是我們需要的。

使用方法:

 #include "matlab.h"

#include "dlltest.h"

#pragma comment(lib,"dlltest")

關鍵代碼:

UpdateData(TRUE);         //重新整理輸入資料

double X[100],Y[100];

CString AA,BB,a;

int i=1;

mxArray *A=NULL;          //初始化矩陣

mxArray *B=NULL;

  AA=m_edit1;           //字元串指派

  BB=m_edit2;

.....//将字元轉化為數字

mlfEnterNewContext(0, 0); //自動管理記憶體

dlltestInitialize();

mlfCeshidll(A,B);         //調用dll檔案中函數

mxDestroyArray(A);        //釋放矩陣記憶體

mxDestroyArray(B);

mlfRestorePreviousContext(0, 0);

例二:将m檔案 轉換成對應的C\C++檔案

1、在MATLAB中編寫如下函數: 

function [x]=gjfcz(A,b) %A=[-1.5 1 2; 4 2 3 ; -3 2 8] %b=[3;5;6] x=A\b

儲存名為gjfcz.m,該函數的功能為求解線形方程組,可參考第四章的内容。

2、在MATLAB的指令視窗輸入以下指令:

mcc –m gjfcz.m

該指令用來生成對應的C檔案和可執行程式。在MATLAB工作目錄下(一般是MATLAB\work)将會生成如下檔案:gjfcz.exe,gjfcz.c,gjfcz.h,gjfcz_main.c,其中gjfcz.c,gjfcz.h是我們需要的檔案。

3、建立名為JXXFC基于對話框的工程,面闆上添加一個按扭。

4、拷貝gjfcz.c,gjfcz.h兩檔案到工程目錄下,并将檔案引入工程(Project->Add to Project->Files)。

5、為按扭添加如下響應代碼:

void CJXXFCDlg::OnButton1() {   static  double Adata[]={-1.5,4,-3,1,2,2,2,3,8};   static  double bdata[]={3,5,6};   double  Xdata[100];   mxArray *A = NULL;//賦初值   mxArray *b = NULL;   mxArray *x = NULL;       mlfEnterNewContext(0, 0);   //建立矩陣   mlfAssign(&A, mlfDoubleMatrix(3, 3, Adata, NULL));   mlfAssign(&b, mlfDoubleMatrix(3, 1, bdata, NULL));   InitializeModule_gjfcz();   x=mlfGjfcz(A,b);//調用gjfcz.c中的函數求解   TerminateModule_gjfcz();   memcpy(Xdata,mxGetPr(x),3*sizeof(double));  // mxGetPr(x)用來得到x的位址,進而獲得matlab輸出   CString R;   R.Format("%f\n%f\n%f",Xdata[0],Xdata[1],Xdata[2]);   MessageBox(R);      mxDestroyArray(A);   mxDestroyArray(b);   mxDestroyArray(x);      mlfRestorePreviousContext(0, 0); }

例三:利用圖形庫畫圖

寫一個簡單的m函數:

function y=huatu_test() x=-10:0.1:10; y=sin(x); plot(x,y,''*'')

檔案儲存為huatu_test.m。

mcc -t -W libhg:dlltest -T link:lib -h libmmfile.mlib huatu_test.m

#include "dlltest.h"

打開dlltest.h檔案,裡面有有關函數的定義,找到其中三個函數:

extern mxArray * mlfHuatu_test(void); extern void dlltestInitialize(void); extern void dlltestTerminate(void);

從函數意思不難知道它們的作用,dlltestInitialize用來初始化dll庫,dlltestTerminate用來結束調用dll,mlfHuatu_test為主程式執行函數。将三個函數拷貝到button響應代碼中,進行修改:

void CCeshiDlg::OnButton1() { dlltestInitialize(); mlfHuatu_test(); dlltestTerminate(); }

利用mcc指令,通過不同的參數設定可以生成不同的檔案,例如:

mcc -B sgl myfun 将myfun.m檔案生成對應的c檔案和使用c圖形庫的可執行程式 mcc -B sglcpp myfun 将myfun.m檔案生成相應的c++檔案和使用c++圖形庫的可執行程式

mcc的參數實際上有很多,例如:

mcc -t -W main -L C -T link:exe -h libmmfile.mlib myfun

該指令是将myfun.m生成可執行c程式

為了簡化選項設定,編譯器提供了宏選項,實際上上述指令利用一個參數就可以了:

mcc -m myfun

該指令和上述指令是等價的,也是用來生成可執行c程式。關于mcc指令詳細參數設定可以參考MATLAB幫助文檔。

大家在使用VC調用MATLAB中遇到什麼問題,可以發電子郵件到[email protected],把遇到的問題說清楚,正在寫書,同時有什麼好的建議,也歡迎發郵件來。

關于程式運作的說明:

1、根據實際情況修改VC中頭檔案和庫檔案的路徑;

2、如果自己編寫的程式圖形不能顯示菜單欄和工具欄,拷貝檔案夾bin到目前目錄下

MCC MATLAB to C/C++ Compiler (Version 3.0).

MCC [-options] fun [fun2 ...] [mexfile1 ...] [mlibfile1 ...]

Translate fun.m to fun.c or fun.cpp, and optionally create any supported

binary file. Write any resulting files into the current directory, by

default.

If more than one M-file is specified, a C or C++ file is generated for each

M-file.

If C or object files are specified, they are passed to MEX or MBUILD along

with any generated C files.

If MEX-files are specified, MCC will generate wrapper code so that calls can

be made from compiled M-files to the specified MEX-files. Also, if a

MEX-file and an M-file with the same base name are located in the same

directory, specifying the MEX-file causes MCC to use it instead of the

M-file. Otherwise MCC favors M-files over MEX-files.

MLIB files describe the functions in a shared library created by MCC (see -W

lib below). Specifying an MLIB file tells MCC to link to the MLIB file's

corresponding shared library whenever it needs to use any of the functions

found in that library. The MLIB file and its corresponding shared library

file must be located within the same directory.

If conflicting options are presented to MCC, the rightmost conflicting

option is used.

OPTIONS:

A <option> Specify annotation. The following table shows valid <option>

strings and their effects:

annotation:all (*) - All lines from source M-file appear as comments 

in generated output file.

annotation:comments - Comments from source M-file appear as comments in 

generated output file.

annotation:none - No text from source M-file appears in generated 

output file.

line:on - #line directives appear in generated output file 

which map lines in source M-code to lines in 

output file.

line:off (*) - No such #line directives are generated.

debugline:on - Run-time error messages report the source file 

name and line number where they occurred.

debugline:off (*) - Run-time error messages do not report any 

information about the source where they occurred.

(*) indicates default setting.

b Generate an MS Excel compatible formula function for the given list of M-files.

B <filename>[:<arg>[,<arg>]] Specify bundle file. <filename> is a text file containing

Compiler command line options. The Compiler behaves as if the "-B

<filename>" were replaced by the contents of the bundle file. Newlines

appearing in these files are allowed and are treated as whitespace.

The MathWorks provides options files for the following:

ccom Used for building a C COM compatible object on Windows

(requires COM Builder)

cexcel Used for building a C MS Excel Compatable COM object on

Windows (requires MATLAB Excel Builder)

csglcom Used for building C COM compatible object on Windows

using the C Graphics Library (requires COM Builder)

csglexcel Used for building a C MS Excel compatible object on Windows

using the C Graphics Library (requires MATLAB Excel Builder)

csglsharedlib

Used for building a C Graphics Library shared library

cppcom Used for building a C++ COM compatible object on Windows

(requires COM Builder)

cppexcel Used for building a C++ MS Excel Compatiable COM object on

Windows (requires MATLAB Excel Builder)

cppsglcom Used for building C++ COM compatible object on Windows

using the Graphics Library (requires COM Builder)

cppsglexcel

Used for building a C++ MS Excel compatible object on Windows

using the Graphics Library (requires MATLAB Excel Builder)

cpplib Used for building a C++ library

csharedlib

Used for building a C shared library

csglsharedlib

Used for building a C Graphics shared library

pcode Used for building MATLAB P-Code files.

sgl Used for building stand-alone C Graphics applications.

sglcpp Used for building stand-alone C++ Graphics Library 

applications.

c C only. Translate M-file to C, but do not produce a MEX-file or 

stand-alone application. This is equivalent to "-T codegen" as the

rightmost argument on the command line.

d <directory> Output directory. All generated files will be put in

<directory>.

F list. List the <option>s available in the next form of the command,

together with their current values and a short explanation.

F <option>:<number> Typesetting format options. Assign the value <number> to

the formatting option <option>. See "F list" for <option>s.

f <filename> Use the specified options file when calling MEX or

MBUILD. This allows you to use different ANSI compilers. This

option is a direct pass-through to the MEX or MBUILD script. See

"External Interfaces" for more information.

G Debug only. Simply turn debugging on, so debugging symbol

information is included.

g Debug. Include debugging symbol information. This option also

includes the -A debugline:on switch. This will have an impact on

performance of the generated code. If you wish to have debugging

information, but do not want the performance degradation

associated with the debug line information use: -g -A

debugline:off. This option also includes the -O none switch. That

switch causes all Compiler optimizations to be turned off. If you

wish to have some optimizations on, you may specify them after the

debug switch.

h Compile helper functions. All M-functions called will be compiled into the resulting MEX-file or stand-alone application.

i When generating a library include only entry points mentioned on the

command line in the list of exported symbols.

I <path> Include path. Add <path> to the list of paths to search for

M-files. The MATLAB path is automatically included when running from

MATLAB, but NOT when running from DOS or the Unix shell. See "help

mccsavepath".

L <option> Language. Specifies target language. <option> can be "C" for C, "Cpp" for C++, or "P" for MATLAB P-code.

l Line. Generates code that reports file name and line numbers on run-time errors. (Equivalent to -A debugline:on)

m Macro that generates a C stand-alone application. This is equivalent to 

the options "-t -W main -L C -h -T link:exe libmmfile.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_m. 

Note: the "-h" means that helper functions will be included.

M "<string>" Pass <string> to the MBUILD or MEX script used to build an

executable. If -M is used multiple times, the rightmost occurrence is

used.

o <outputfilename> Output name. Set the name of the final executable output

(MEX or stand-alone application) to <outputfilename>. A suitable,

possibly platform-dependent, extension is added to <outputfilename>

(e.g., ".exe" for PC stand-alone applications, ".mexsol" for Solaris

MEX-files).

O <optimization> Optimization. There are three possibilities:

<optimization class>:[on|off] - Turns the class on or off 

For example: -O fold_scalar_mxarrays:on

list - Lists the available optimization classes.

<optimization level> - Uses a bundle file called

opt_bundle_<level> to determine which optimizations are on or off.

For example "-O all" looks for a bundle file called opt_bundle_all

and uses the switches present. The current optimization levels

are "all" and "none". The default is to have all optimizations

on.

p Macro that generates C++ stand-alone application. This is equivalent to

the options "-t -W main -L Cpp -h -T link:exe libmmfile.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_p. 

Note: the "-h" means that helper functions will be included.

S Macro that generates Simulink C-MEX S-Function. This is equivalent to 

the options "-t -W simulink -L C -T link:mex libmatlbmx.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_S. 

Note: the absence of "-h" means that helper functions will not be 

included.

t Translate M code to target language. Translate any M-functions specified on the command line to C or C++ functions. This option is included in all macro options. Omitting it allows the generation of wrapper C/C++ files without generating the C/C++ files corresponding to M-files.

T <option> Specify target phase and type. The following table shows valid <option> strings and their effects:

codegen - translate M-files to C/C++ files and generate a 

wrapper file. (This is the default -T setting.)

compile:mex - same as codegen, plus compile C/C++ files to object

form suitable for linking into a Simulink 

S-function MEX-file.

compile:mexlibrary - same as codegen, plus compile C/C++ files to object form suitable for linking into an ordinary (non-S-function) MEX-file.

compile:exe - same as codegen, plus compile C/C++ files to object form suitable for linking into a stand-alone executable.

compile:lib - same as codegen, plus compile C/C++ files to object form suitable for linking into a shared library/DLL.

link:mex - same as compile:mex, plus link object files into a Simulink S-function MEX-file.

link:mexlibrary - same as compile:mexlibrary, plus link object files into an ordinary (non S-function) MEX-file.

link:exe - same as compile:exe, plus link object files into a stand-alone executable.

link:lib - same as compile:lib, plus link object files into a shared library/DLL.

u <number> Specify that the number of inputs to a generated Simulink

S-function should be <number>. Valid only if either "-S" or "-W

simulink" option has also been specified.

v Verbose. Show compilation steps.

w list. List the <msg> strings allowed in the next form of the command,

together with the full text of the warning messages to which they

correspond.

w <option>[:<msg>] Warnings. The possible options are "enable", "disable",

and "error". If "enable:<msg>" or "disable:<msg>" is specified, enable

or disable the warning associated with <msg>. If "error:<msg>" is

specified, enable the warning associated with <msg> and treat any

instances of that warning as an error. If the <option> but not ":<msg>"

is specified, the Compiler applies the action to all warning

messages. For backward compatibility with previous Compiler revisions,

"-w" (with no option) is the same as "-w enable".

W <option> Wrapper functions. Specify which type of wrapper file should be generated by the Compiler. <option> can be one of "mex",

"main", "simulink", "lib:<string>","com:<component-name>,<class-name>,<version>", or "none"(default). For the lib wrapper, <string> contains the name of the shared library to build. When generating a "lib" wrapper, MCC also creates an MLIB file describing the functions in the shared library.

x Macro that generates a MEX-file. This is equivalent to the options "-t -W mex -L C -T link:mexlibrary libmatlbmx.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_x. Note: the absence of "-h" means that helper functions will not be included.

y <number> Specify that the number of outputs from a generated Simulink

S-function should be <number>. Valid only if either "-S" or 

"-W simulink" option has also been specified.

Y <license.dat file> Override default license.dat file with specified

argument.

z <path> Specify the path to use for library and include files.

This option uses the specified path for the Compiler libraries

instead of MATLABROOT.

? Help. Display this help message.

EXAMPLES:

Make a C translation and a MEX-file for myfun.m:

mcc -x myfun

Make a C translation and a stand-alone executable for myfun.m:

mcc -m myfun

Make a C++ translation and a stand-alone executable for myfun.m:

mcc -p myfun

Make a C translation and a Simulink S-function for myfun.m

(using dynamically sized inputs and outputs):

mcc -S myfun

Make a C translation and a Simulink S-function for myfun.m

(explicitly calling for one input and two outputs):

mcc -S -u 1 -y 2 myfun

Make a C translation and stand-alone executable for myfun.m. Look for

myfun.m in the directory /files/source, and put the resulting C files and

executable in the directory /files/target:

mcc -m -I /files/source -d /files/target myfun

Make a C translation and a MEX-file for myfun.m. Also translate and include 

all M-functions called directly or indirectly by myfun.m. Incorporate the 

full text of the original M-files into their corresponding C files as C 

comments:

mcc -x -h -A annotation:all myfun

Make a generic C translation of myfun.m:

mcc -t -L C myfun

Make a generic C++ translation of myfun.m:

mcc -t -L Cpp myfun

Make a C MEX wrapper file from myfun1.m and myfun2.m:

mcc -W mex -L C libmatlbmx.mlib myfun1 myfun2

Make a C translation and a stand-alone executable from myfun1.m and myfun2.m

(using one mcc call):

mcc -m myfun1 myfun2

Make a C translation and a stand-alone executable from myfun1.m and myfun2.m

(by generating each output file with a separate MCC call). Note that the

MLIB file "libmmfile.mlib" only needs to be specified when generating a

wrapper file, and when linking the final executable:

mcc -t -L C myfun1 % yields myfun1.c

mcc -t -L C myfun2 % yields myfun2.c

mcc -W main -L C myfun1 myfun2 libmmfile.mlib % yields myfun1_main.c

mcc -T compile:exe myfun1.c % yields myfun1.o

mcc -T compile:exe myfun2.c % yields myfun2.o

mcc -T compile:exe myfun1_main.c % yields myfun1_main.o

mcc -T link:exe myfun1.o myfun2.o myfun1_main.o libmmfile.mlib

Make a shared/dynamically linked library called "liba" from a0.m and a1.m,

where neither a0 nor a1 calls functions in libmmfile:

mcc -t -W lib:liba -T link:lib a0 a1

Make a shared/dynamically linked library called "liba" from a0.m and

a1.m, where at least one of a0 or a1 calls at least one function in

libmmfile. Define LIBMMFILE to be 1 when compiling the C code.:

mcc -t -W lib:liba -T link:lib a0 a1 libmmfile.mlib -M "-DLIBMMFILE=1"

Make a C translation and a stand-alone graphics library executable from 

myfun.m (using one MCC call):

mcc -B sgl myfun1 

Make a C++ translation and a stand-alone graphics library executable from 

myfun.m (using one MCC call):

mcc -B sglcpp myfun1 

Make a shared/dynamically linked library called "liba" from a0.m and a1.m

that makes calls into the MATLAB C/C++ Graphics Library:

mcc -B sgl -t -W libsgl:liba -T link:lib a0 a1

繼續閱讀