MATLAB: How to build a C++ program using MATLAB Engine in Visual Studio

2017buildcengineinMATLABMATLAB Compilerprogramsolutionstudiovisual

I am trying to build a C++ Engine program using Visual Studio 2017. I am following the documentation page:
How can I do this in Visual Studio 2017?

Best Answer

You can test your build environment first using the "mex" command. You can also get a sample file "main.cpp" file from the "Test Your Build Environment" documentation page in:
Below is a guideline on building C++ Engine program using Visual Studio 2017 which uses the "main.cpp" from the aforementioned documentation link.
Create a new Visual C++ project from existing code
Click on "File > New > Project From Existing Code..." in the menu of Visual Studio 2017.
When it asks for:
  • What type of project would you like to create? Choose "Visual C++".
  • Project file location? Choose the path to a directory which contains only "main.cpp" file and no other files, e.g. "E:\Project".
  • Project name: Choose any name, e.g. "Project".
  • Use Visual Studio: Choose "Console application project"
Then change the platform to x64, see the screenshot below:
Set the correct properties for the project
Inside Solution Explorer, right click on the project and choose "Properties".
Set the path to the MATLAB header files
Then click on "Configuration Properties > C / C++ > General", and set (see screenshot below):
  • Additional Include Directories: the path to "<matlabroot>\extern\include", e.g. "E:\MATLAB64\R2018b\extern\include"
Set the path to the MATLAB static library files
Then click on "Configuration Properties > Linker > General" and set (see screenshot below):
  • Additional Library Directories: the path to the "<matlabroot>\extern\lib\win64\microsoft", e.g. "E:\MATLAB64\R2018b\extern\lib\win64\microsoft"
Set the dependencies in the Visual Studio linker
Then click on "Configuration Properties > Linker > Input" and set (see screenshot below):
  • Additional Dependencies: "libMatlabEngine.lib;libMatlabDataArray.lib;%(AdditionalDependencies)"
Then finally setup the environmental variable for the debugging
Click on "Configuration Properties > Debugging > Environment" and set (see screenshot below):
  • Environment: "PATH=<matlabroot>\extern\bin\win64;%PATH%"
  • e.g. "PATH=E:\MATLAB64\R2018b\extern\bin\win64;%PATH%".
Building and running the project
In "main.cpp" line 34 (it says "return 0;") put a break point.
Press F5 or the "Local Windows Debugger" button to start the debugger. It will build the project automatically and start the compiled console application, see the screenshot below.
If you have built the project in the past, you can rebuild it by going to "Build > Rebuild Solution".
We have a documentation page which mentions what is needed to be done in order to compile MATLAB Engine applications in an IDE. This is available in the documentation page in: