C++ Code Generation - MATLAB & Simulink (original) (raw)
Main Content
MATLAB® Coder™ enables you to either generate C or C++ code. The code generator produces C code by default. Generated C++ code can use functionality not available in the C language that can make the C++ code more readable and easier to use.
Generate C++ Code
To generate C++ code, follow the code generation workflow. See Overview of Code Generation Using MATLAB Coder.
To instruct the code generator to produce C++ code, use one of these approaches:
- Use the
-lang:c++
option with the codegen command at the command line. - Set the
TargetLang
property in a code configuration object to"C++"
. - In the Code Generation Settings, set the Language parameter to
C++
. - In the MATLAB Coder app, click the Language button in theMATLAB Coder toolstrip and select
C++
.
C++ Language Features Supported in Generated Code
To learn about code generation that utilizes key C++ language features, refer to these help topics:
These examples illustrate the use of these functionalities:
- Generate C++ Classes for MATLAB Classes That Model Simple and Damped Oscillators
- Integrate Multiple Generated C++ Code Projects
Additional Differences Between Generated C Code and C++ Code
If you separately generate C and C++ code for the same MATLAB function, and inspect the generated source code, then there are implementation differences. These are some notable differences:
- The generated C++ code contains overloaded functions or methods that have the same name but support multiple signatures. The C language does not support overloading of functions.
- The generated C++ code reuses the same identifier name across different namespace hierarchies. For example, the same type name
myType
can appear in two different namespaces hierarchies with top-level namespacesmyNamespace_1
andmyNamespace_2
. The C language does not support namespaces and such reuse of identifier names. - In generated C code, the function headers contain
#ifdef __cplusplus
include guards that specify theextern "C"
identifier for the generated C functions. The compiler and linker use these identifiers in building C code as part of a C++ project. - Generated C++ code uses
.cpp
file extensions for the C++ files and.h
extensions for the header files. Generated C code uses.c
and.h
extensions. - The generated C++ code uses some C++ casts, like
static_cast
, which are more explicit than the casting syntax in C. - The generated code defines values for
Inf
andNaN
based on different mechanisms for C++ and C. - Generated C++ code uses the custom data types as described in Mapping MATLAB Types to Types in Generated Code.
- Generated C++ code uses different libraries than generated C code. For example, the default language standard for C++ and C is described in Change Language Standard Used for Code Generation.