Main Content

Build C++ Source Code Generated from MATLAB Code Using CMake Toolchain

CMake is a third-party, open-source tool for build process management. In this example, when generating C++ source code for a simple MATLAB® function, you instruct the code generator to also produce a CMakeLists.txt file. This file does not depend on specific build tools and contains the build instructions for the generated code in a platform-independent CMake language.

After generating C++ source code and the CMakeLists.txt file, invoke the cmake command to:

  1. Use the CMakeLists.txt file to generate standard build files. These include makefile and Ninja, as well as Microsoft® Visual Studio® and Xcode project builds.

  2. Run the compiler and other build tools to create an executable or a library.

Alternatively, you can use CMake and the associated CMakeLists.txt file with command-line tools and IDEs such as Microsoft® Visual Studio, Microsoft Visual Studio Code, Xcode, and CLion.

In addition to the ability to generate CMakeLists.txt files that do not depend on specific build tools, the code generator also provides CMake toolchain definitions for specific compilers and build systems. For more information on this alternative workflow, see Configure CMake Build Process.

Define MATLAB Entry-Point Function

Define a simple MATLAB entry-point function myfun for which you intend to generate and build C++ code.

type myfun.m
function a = myfun(a) %#codegen
a = a + sqrt(a);
end

Generate C++ Source Code

Generate C++ source code only. Specify the type of the input as a scalar double. Specify the name of the code generation folder as myfun_trial_codegen.

codegen -config:lib -lang:c++ -c myfun -args 0 -d myfun_trial_codegen
Code generation successful.

Because you used the same variable as both an input and an output in your MATLAB code, the generated C++ entry-point function uses a pointer to pass and return this variable. Therefore, the function has this signature:

void myfun(double *a)

In addition to the entry-point code, the code generator also produces example main.cpp and main.h files in the myfun_trial_codegen/examples folder. You copy and modify these example files in the next step.

Define C++ Main Function

Copy the example main.cpp and main.h files generated in the previous step to your current working folder. Modify the main function so that it accepts a scalar double input, invokes the generated C++ entry-point function myfun, and prints the output of myfun.

type main.cpp
#include "main.h"
#include "myfun.h"
#include "myfun_terminate.h"

int main(int argc, char* argv[])
{
  if (argc < 2) {
    std::cout << "Usage: " << argv[0] << " number" << std::endl;
    return 1;
  }

  double inputValue = atof(argv[1]);
  double parameter = inputValue;
  myfun(&parameter);
  double outputValue = parameter;
    
  std::cout << "Adding the number " << inputValue << " to its own square root produces " << outputValue
            << std::endl;

  myfun_terminate();
  return 0;
}

Generate C++ Source Code and CMakeLists.txt File for Building Executable

Define a code generation configuration object cfg for building a C++ executable. To include the main.h and main.cpp files in the code generation process, set the CustomInclude and CustomSource properties, respectively.

Because you will build the generated code in the next step using CMake, configure the code generator to produce:

  • Source code only by setting the GenCodeOnly property to true.

  • A CMakeLists.txt file by setting the Toolchain property to "CMake".

cfg = coder.config("exe");
cfg.TargetLang = "C++";

cfg.CustomSource = "main.cpp";
cfg.CustomInclude = {pwd};

cfg.GenCodeOnly = true;
cfg.Toolchain = "CMake";

Generate source code and the CMakeLists.txt file by running the codegen command. Specify the name of the code generation folder as myfun_codegen.

codegen -config cfg myfun -args 0 -d myfun_codegen
Code generation successful.

Approach 1: Switch to IDE of Your Choice

CMake and the associated CMakeLists.txt file are widely used for building C++ code and you can use them directly with command-line tools and IDEs such as Microsoft Visual Studio, Microsoft Visual Studio Code, Xcode, and CLion. So, at this point in the workflow, you can open the code generation folder myfun_codegen in the IDE of your choice and proceed with configuring, building, and debugging your C++ project.

For example, if you use Visual Studio Code, run this command:

system("code ./myfun_codegen");

Approach 2: Call cmake at MATLAB Command Line to Build Executable

Create a build folder myfun_build if it does not already exist. Navigate to that folder.

if (~exist("myfun_build","dir"))
    mkdir myfun_build
end
cd myfun_build

Invoke the cmake command to build a project for the available toolchain on your system. In this example, cmake builds a project for the Visual Studio 2019 toolchain. Therefore, it creates a myfun.vcxproj file, along with other supporting files, in the myfun_build folder.

system("cmake ../myfun_codegen");
-- Selecting Windows SDK version 10.0.18362.0 to target Windows 10.0.22621.
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/aghosh/Documents/ExampleManager/aghosh.sandbox2/coder-ex42771556/myfun_build

Invoke the cmake command again to build this project and create an executable myfun in your main working folder.

system("cmake --build .");
Microsoft (R) Build Engine version 16.4.0+e901037fe for .NET Framework 
Copyright (C) Microsoft Corporation. All rights reserved. 
 
  main.cpp 
  myfun.cpp 
  myfun_initialize.cpp 
  myfun_terminate.cpp 
  Generating Code... 
  myfun.vcxproj -> C:\Users\aghosh\Documents\ExampleManager\aghosh.sandbox2\coder-ex42771556\myfun.exe 
  \#\#\# Created executable: C:/Users/aghosh/Documents/ExampleManager/aghosh.sandbox2/coder-ex42771556/myfun.exe 

Run Generated Executable

Run the generated executable myfun with sample input.

cd ..;
if isunix
    system('./myfun 144');
elseif ispc
    system('myfun 144');
else
    disp('Platform is not supported')
end
Adding the number 144 to its own square root produces 156 

Related Topics