2018/03/10

Matlab: Run Hello World files written in C/C++ with MEX command

To run C/C++ files from Matlab, use the MEX command.
Create the files in C or C++:

C (hello.c)

#include"mex.h"
#include<stdio.h>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    printf("Hello, World!\n");
}


C++ (helloCPP.cpp)

#include"mex.h"
#include <iostream>

using namespace std;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    cout << "Hello, World!\n";

}

The mexFunction in either of the C or C++ example above is similar to the main function in pure C or C++ programs. Type your main program here such as printf in C or cout in C++.

Execute the files with the MEX command in Matlab such as below:

C
mex hello.c
hello

C++
mex helloCPP.cpp
helloCPP

Results in the Matlab command window:


References

Matlab 教材:測試 MEX-file
C language with Mac: Hello World with Mac's Terminal
C++ with Mac: Hello World with Mac's Terminal

沒有留言:

張貼留言