주요 콘텐츠

명령줄에서 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

averagingFilterML 함수 선언 뒤에 %#codegen 지시문을 추가합니다. 이 지시문은 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++는 정적 유형 언어이므로 코드 생성기는 코드 생성 중에 생성된 코드에 있는 모든 변수의 클래스와 크기를 확인해야 합니다. 입력 유형을 지정할 수 있는 방법 중 하나는 arguments 블록을 사용하는 것입니다. 입력 유형 지정에 대한 다른 방법에 대해 알아보려면 진입점 함수 입력값의 유형 지정하기 항목을 참조하십시오.

입력 인수 x를 double형으로 구성된 unbounded(크기 비제한) 행 벡터로 정의하려면 함수 선언 뒤에 다음 코드를 추가합니다.

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 함수를 생성합니다. C++ MEX 함수를 생성하도록 코드 생성기에 지시하려면 -lang:C++ 옵션을 사용하십시오.

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

원래 MATLAB 함수에 전달한 것과 동일한 입력값으로 MEX 함수를 테스트합니다. 이 예제에서는 두 함수의 출력값이 머신 엡실론 내에서 동일합니다.

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 함수를 살펴봅니다. 코드 생성기는 폴더 codegen/lib/averagingFilter/examples에 예제 CPP 파일과 H 파일을 생성합니다.

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 함수는 생성 코드에 입력을 전달하고 생성 코드에서 출력을 받는 방법을 보여줍니다.

examples 하위 폴더에서 파일 main.cmain.h를 수정하지 마십시오. 예제 main 함수를 사용하기 전에, 예제 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++ 실행 파일을 생성하도록 코드 생성기에 지시합니다. 명령줄에서 파일 이름을 지정하여 codegen 명령에 사용자 지정 main.cpp 소스 코드를 포함하도록 지시합니다. 코드 생성기는 작업 폴더에 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

참고 항목

|

도움말 항목