メインコンテンツ

コマンド ラインでの C++ 実行可能ファイルの生成

この例では、codegenコマンドを使用して MATLAB® 関数から C++ 実行可能ファイルを生成する方法を示します。この例では、コード生成用にエントリポイント関数を準備し、入力の型を決定してから、MEX 関数、例の C++ main 関数、および単純な C++ 実行可能ファイルを生成します。コード生成の基礎については、Generate Deployable Standalone Code by Using the MATLAB Coder Appを参照してください。

MATLAB 関数の確認とサンプル データの生成

MATLAB 関数 averagingFilterML を確認します。この関数は、平均化フィルターを使用して入力信号のノイズを除去します。信号値の入力ベクトルを受け取り、入力ベクトルと同じサイズの、フィルター処理された値の出力ベクトルを返します。関数 averagingFilterML は変数 slider を使用して 16 の信号値のスライディング ウィンドウを表し、各ウィンドウ位置の平均信号値を計算します。

type averagingFilterML
function y = averagingFilterML(x)
slider = zeros(16,1);
for i = 1:numel(x)
    slider(2:end) = slider(1:end-1); % move one position in the buffer
    slider(1) = x(i); % Add a new sample value to the buffer
    y(i) = sum(slider)/numel(slider); % write the average of the current window to y
end
end

ノイズを含む正弦波を生成し、averagingFilterML を使用してノイズを含むデータをフィルター処理してプロットします。

v = 0:0.00614:2*pi;
x = sin(v) + 0.3*rand(1,numel(v));
filtered_ML = averagingFilterML(x);
plot(x,"red");
hold on
plot(filtered_ML,"blue");
xlim([0 1000])
hold off;

Figure contains an axes object. The axes object contains 2 objects of type line.

コード生成用のエントリポイント関数の準備

コード生成用にエントリポイント関数を準備します。"エントリポイント関数" は、コード生成の対象にする他のすべての MATLAB 関数を呼び出す最上位の関数です。この例では、averagingFilterML をエントリポイント関数として使用します。

コード生成用に averagingFilterML を準備するには、関数を編集します。

edit averagingFilterML

%#codegen 命令を averagingFilterML 関数の宣言の後に追加します。この命令は、コード生成に固有の警告およびエラーを特定するように MATLAB コード アナライザーに指示します。この例では、出力引数 y を使用する前に完全に定義しなければならないことが、コード アナライザーによって示されます。コード アナライザーによって実行されるチェックの詳細については、MATLAB for Code Generation Messagesを参照してください。

Function averagingFilterML, showing Code Analyzer error

配列の要素にアクセスするには、その前にコード ジェネレーターが配列のサイズと型を判別できなければなりません。この例では、要素 y(i) を更新する前に、配列 y のサイズと型を定義しなければなりません。zeros関数を使用して、y が double の 1 行 x 列の配列であることを示すことができます。関数宣言の後に、次のコード行を追加します。

y = zeros(size(x));

この変更を行った後、コード アナライザーは、コード内の潜在的なコード生成エラーをさらに特定しません。ファイル averagingFilterCG.m には更新されたコードが含まれています。

coder.screener関数を使用して、コード生成の準備状態ツールを実行します。このツールを使用して、コード生成でサポートされていない関数や機能が MATLAB コードに含まれていないかをチェックします。このツールによって実行されるチェックの詳細については、コード生成の準備状態ツールを参照してください。

この例では、コード生成の準備状態ツールでは、averagingFilterCG 関数内で、サポートされていない関数や機能は見つかりません。

coder.screener("averagingFilterCG")

Code generation readiness tool, showing no errors

入力の型の指定

エントリポイント関数の入力の型を指定します。C および C++ は静的に型付けされる言語であるため、コード ジェネレーターはコード生成中に、生成されたコード内のすべての変数のクラスとサイズを決定する必要があります。入力の型を指定する方法の 1 つの方法として、argumentsブロックを使用できます。入力の型の指定に関する他の方法については、エントリポイント関数の入力の型の指定を参照してください。

関数宣言の後に次のコードを追加して、入力引数 x を double の制限なしの行ベクトルとして定義します。

arguments

x (1,:) double

end

ファイル averagingFilter.m には更新されたコードが含まれています。

type averagingFilter
function y = averagingFilter(x) %#codegen
arguments
    x (1,:) double
end
y = zeros(size(x));
slider = zeros(16,1);
for i = 1:numel(x)
    slider(2:end) = slider(1:end-1); % move one position in the buffer
    slider(1) = x(i); % Add a new sample value to the buffer
    y(i) = sum(slider)/numel(slider); % write the average of the current window to y
end
end

MEX 関数の生成と実行

エントリポイント関数から MEX 関数を生成します。MEX 関数は、MATLAB 内から実行できる C または C++ 実行可能ファイルです。生成された MEX 関数を実行して、生成されたコードの動作が元の MATLAB コードと同じであることを確認します。

生成された MEX 関数を実行すると、スタンドアロン コードでは診断が困難な実行時エラーを検出できるため、ベスト プラクティスとして、このステップを実行することをお勧めします。たとえば、MEX 関数には、既定でメモリ整合性チェックが含まれています。これらのチェックは、配列の範囲と次元のチェックを実行し、MATLAB 関数に対して生成されたコード内のメモリ整合性の違反を検出します。

既定では、codegen コマンドは作業フォルダーに C の MEX 関数を生成します。-lang:C++ オプションを使用して、C++ の MEX 関数を生成するようにコード ジェネレーターに指示します。

codegen averagingFilter -lang:c++
Code generation successful.

元の MATLAB 関数に渡したのと同じ入力を使用して MEX 関数をテストします。この例では、2 つの関数の出力は計算機イプシロン内で等価です。

filtered_MEX = averagingFilter_mex(x);
all(abs(filtered_ML-filtered_MEX)) < eps
ans = logical
   1

例の C++ main 関数の生成

例の C++ main 関数を生成します。コード ジェネレーターは、スタンドアロン コードの生成時に、例の C または C++ の main 関数を生成します。例の main 関数は、生成された C または C++ 関数の呼び出し方法を示しているため、アプリケーションのテンプレートとして使用できます。-config:lib オプションと -lang:c++ オプションを指定した codegen コマンドを使用し、スタンドアロン C++ スタティック ライブラリを生成します。

codegen -config:lib -lang:c++ averagingFilter
Code generation successful.

例の C++ の main 関数を確認します。コード ジェネレーターは、例の CPP ファイルおよび H ファイルをフォルダー codegen/lib/averagingFilter/examples 内に作成します。

type(fullfile("codegen","lib","averagingFilter","examples","main.cpp"))
//
// Prerelease License - for engineering feedback and testing purposes
// only. Not for sale.
// File: main.cpp
//
// MATLAB Coder version            : 26.1
// C/C++ source code generated on  : 24-Jan-2026 17:07:36
//

/*************************************************************************/
/* This automatically generated example C++ main file shows how to call  */
/* entry-point functions that MATLAB Coder generated. You must customize */
/* this file for your application. Do not modify this file directly.     */
/* Instead, make a copy of this file, modify it, and integrate it into   */
/* your development environment.                                         */
/*                                                                       */
/* This file initializes entry-point function arguments to a default     */
/* size and value before calling the entry-point functions. It does      */
/* not store or use any values returned from the entry-point functions.  */
/* If necessary, it does pre-allocate memory for returned values.        */
/* You can use this file as a starting point for a main function that    */
/* you can deploy in your application.                                   */
/*                                                                       */
/* After you copy the file, and before you deploy it, you must make the  */
/* following changes:                                                    */
/* * For variable-size function arguments, change the example sizes to   */
/* the sizes that your application requires.                             */
/* * Change the example values of function arguments to the values that  */
/* your application requires.                                            */
/* * If the entry-point functions return values, store these values or   */
/* otherwise use them as required by your application.                   */
/*                                                                       */
/*************************************************************************/

// Include Files
#include "main.h"
#include "averagingFilter.h"
#include "averagingFilter_initialize.h"
#include "averagingFilter_terminate.h"
#include "coder_array.h"

// Function Declarations
static coder::array<double, 2U> argInit_1xUnbounded_real_T();

static double argInit_real_T();

// Function Definitions
//
// Arguments    : void
// Return Type  : coder::array<double, 2U>
//
static coder::array<double, 2U> argInit_1xUnbounded_real_T()
{
  coder::array<double, 2U> result;
  // Set the size of the array.
  // Change this size to the value that the application requires.
  result.set_size(1, 2);
  // Loop over the array to initialize each element.
  for (int idx1{0}; idx1 < result.size(1); idx1++) {
    // Set the value of the array element.
    // Change this value to the value that the application requires.
    result[idx1] = argInit_real_T();
  }
  return result;
}

//
// Arguments    : void
// Return Type  : double
//
static double argInit_real_T()
{
  return 0.0;
}

//
// Arguments    : int argc
//                char **argv
// Return Type  : int
//
int main(int, char **)
{
  // Initialize the application.
  // You do not need to do this more than one time.
  averagingFilter_initialize();
  // Invoke the entry-point functions.
  // You can call entry-point functions multiple times.
  main_averagingFilter();
  // Terminate the application.
  // You do not need to do this more than one time.
  averagingFilter_terminate();
  return 0;
}

//
// Arguments    : void
// Return Type  : void
//
void main_averagingFilter()
{
  coder::array<double, 2U> x;
  coder::array<double, 2U> y;
  // Initialize function 'averagingFilter' input arguments.
  // Initialize function input argument 'x'.
  x = argInit_1xUnbounded_real_T();
  // Call the entry-point 'averagingFilter'.
  averagingFilter(x, y);
}

//
// File trailer for main.cpp
//
// [EOF]
//

例の C++ main 関数の変更

例の main.cpp ファイルを作業ディレクトリにコピーし、アプリケーションに合わせて変更します。生成された main 関数の例を、main 関数を作成するための開始点として使用します。main の例は、生成されたコードへの入力とコードからの出力を渡す方法を示しています。

ファイル main.cmain.hexamples サブフォルダーで変更しないでください。main 関数の例を使用する前に、メイン ソース ファイルとヘッダー ファイルの例をビルド フォルダー以外の場所にコピーします。アプリケーションの要件を満たすように新しい場所でファイルを変更します。

この例では、作業ディレクトリ内のファイル main.cpp に、簡略化された C++ main 関数が含まれています。

type main.cpp
#include "averagingFilter.h"
#include "averagingFilter_initialize.h"
#include "averagingFilter_terminate.h"
#include "coder_array.h"
#include <iostream>

int main()
{
    coder::array<double, 2U> x = {1.0, 2.0};
    coder::array<double, 2U> y;
    averagingFilter_initialize();
    averagingFilter(x, y);
    averagingFilter_terminate();
    
    std::cout << "Execution completed";
       
    return 0;
}

C++ 実行可能ファイルの生成とテスト

-config:exe オプションと -lang:c++ オプションを指定した codegen コマンドを使用して、C++ 実行可能ファイルを生成するようにコード ジェネレーターに指示します。コマンド ラインでファイル名を指定して、カスタムの main.cpp ソース コード ファイルを含めるように codegen コマンドに指示します。コード ジェネレーターは、作業フォルダーに averagingFilter 実行可能ファイルを作成します。

codegen -config:exe -lang:c++ averagingFilter main.cpp
Code generation successful.

MATLAB で実行可能ファイルを実行するには、systemコマンドを使用します。ispc関数を使用して、適切な system コマンドを選択します。

if ispc
    system("averagingFilter.exe")
else
    system("./averagingFilter")
end
Execution completed
ans = 
0

参考

|

トピック