compiler.build.cppSharedLibrary - Create C++ shared library - MATLAB (original) (raw)

Create C++ shared library

Since R2021a

Syntax

Description

compiler.build.cppSharedLibrary([FunctionFiles](#mw%5F11246fa9-044a-42ab-88d5-09831b164dd4)) creates a C++ shared library using the MATLAB® files specified by FunctionFiles. Install a supportedC++ compiler before using this function.

example

compiler.build.cppSharedLibrary([FunctionFiles](#mw%5F11246fa9-044a-42ab-88d5-09831b164dd4),[Name,Value](#namevaluepairarguments)) creates a C++ shared library with options specified using one or more name-value arguments. Options include the interface API, library name, and output directory.

example

compiler.build.cppSharedLibrary([opts](#mw%5Ff8799182-ccd0-40ed-a8cf-c101c37d3c6c)) creates a C++ shared library with options specified using acompiler.build.CppSharedLibraryOptions object opts. You cannot specify any other options using name-value arguments.

example

[results](#mw%5F04a1909f-de05-45b7-a77c-3d78257dae89) = compiler.build.cppSharedLibrary(___) returns build information as a compiler.build.Results object using any of the input argument combinations in previous syntaxes. The build information consists of the build type, paths to the compiled files, and build options.

example

Examples

collapse all

Create a C++ shared library using a function file that adds two matrices.

In MATLAB, locate the MATLAB function that you want to deploy as a C++ library. For this example, use the file addmatrix.m located in_`matlabroot`_\extern\examples\compilersdk\c_cpp\matrix.

appFile = fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix','addmatrix.m');

Build a C++ library using the compiler.build.cppSharedLibrary command.

compiler.build.cppSharedLibrary(appFile);

The build function generates the following files within a folder namedaddmatrixcppSharedLibrary in your current working directory:

To implement your shared library, see Implement C++ MATLAB Data API Shared Library with Sample Application.

Create a C++ library and customize it using name-value arguments.

For this example, use the file addmatrix.m located in_`matlabroot`_\extern\examples\compilersdk\c_cpp\matrix.

appFile = fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix','addmatrix.m');

Save the following code in a sample file namedaddmatrixSample1.m:

a1 = [1 4 7; 2 5 8; 3 6 9]; a2 = a1; a = addmatrix(a1, a2);

Build a C++ library using the compiler.build.cppSharedLibrary command. Use name-value arguments to specify the library name, add a sample file, and use the mwArray interface.

compiler.build.cppSharedLibrary(appFile,'LibraryName','mwa_addmatrix', ... 'SampleGenerationFiles','addmatrixSample1.m', ... 'Interface','mwarray');

The build function creates the following files within a folder namedmwa_addmatrixcppSharedLibrary in your current working directory:

To implement your shared library, see Implement C++ mwArray API Shared Library with C++ Sample Application.

Create multiple C++ libraries using a compiler.build.CppSharedLibraryOptions object.

For this example, use the file addmatrix.m located in_`matlabroot`_\extern\examples\compilersdk\c_cpp\matrix.

appFile = fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix','addmatrix.m');

Create a CppSharedLibraryOptions object usingappFile. Use name-value arguments to specify a common output directory, enable debug symbols, and enable verbose output.

opts = compiler.build.CppSharedLibraryOptions(appFile, ... 'OutputDir','D:\Documents\MATLAB\work\CppLibraryBatch', ... 'DebugBuild','on','Verbose','on')

opts =

CppSharedLibraryOptions with properties:

            Interface: 'matlab-data'
       LibraryVersion: '1.0.0.0'
SampleGenerationFiles: {}
        FunctionFiles: {'C:\Program Files\MATLAB\R2025a\extern\examples\compilersdk\c_cpp\addmatrix.m'}
           DebugBuild: on
          LibraryName: 'magicsquare'
      AdditionalFiles: {}
  AutoDetectDataFiles: on
ExternalEncryptionKey: [0×0 struct]
     ObfuscateArchive: off
      SecretsManifest: ''
      SupportPackages: {'autodetect'}
              Verbose: on
            OutputDir: 'D:\Documents\MATLAB\work\CppLibraryBatch'

Build the C++ shared library using the CppSharedLibraryOptions object.

compiler.build.cppSharedLibrary(opts);

To create a new library using the function file subtractmatrix.m with the same options, use dot notation to modify the FunctionFiles argument of the existing CppSharedLibrary object before running the build function again.

opts.FunctionFiles = fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix','subtractmatrix.m'); compiler.build.cppSharedLibrary(opts);

By modifying the FunctionFiles argument and recompiling, you can compile multiple libraries using the same options object.

Create a C++ library and save information about the build type, compiled files, support packages, and build options to a compiler.build.Results object.

Compile using the file magicsquare.m.

results = compiler.build.cppSharedLibrary('magicsquare.m')

results =

Results with properties:

          BuildType: 'cppSharedLibrary'
              Files: {2×1 cell}

IncludedSupportPackages: {} Options: [1×1 compiler.build.CppSharedLibraryOptions] RuntimeDependencies: [1×1 compiler.runtime.Dependencies]

The Files property contains the paths to the v2 folder and GettingStarted.html.

Input Arguments

collapse all

Files implementing MATLAB functions, specified as a character vector, a string scalar, a string array, or a cell array of character vectors. File paths can be relative to the current working directory or absolute. Files must have one of the following extensions: .m, .p, .mlx, or .mexa64.

Example: ["myfunc1.m","myfunc2.m"]

Data Types: char | string | cell

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: 'Verbose','on'

Additional files and folders to include in the C++ shared library, specified as a character vector, a string scalar, a string array, or a cell array of character vectors. Paths can be relative to the current working directory or absolute.

Example: 'AdditionalFiles',["myvars.mat","data.txt"]

Data Types: char | string | cell

Flag to automatically include data files, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent totrue, and 'off' is equivalent tofalse. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

Example: 'AutoDetectDataFiles','off'

Data Types: logical

Flag to enable debug symbols, specified as 'on' or'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent totrue, and 'off' is equivalent tofalse. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

Example: 'DebugBuild','on'

Data Types: logical

Since R2024b

Paths to the external AES encryption key and MEX key loader files, specified as a scalar struct with exactly two row char vector or string scalar fields named EncryptionKeyFile andRuntimeKeyLoaderFile, respectively. File paths can be relative to the current working directory or absolute.

For C++ shared libraries, as an alternative to specifying both key and MEX loader at compile time, you can specify only the encryption key and setRuntimeKeyLoaderFile as an empty string. You then provide the hex encoded 64 byte decryption key at runtime in your C++ application as an argument for the initMATLABLibrary function using the MATLAB Data API or the InitializeWithKey function using the MWArray API.

For example, specify the encryption key as encrypt.key and loader file as loader.mexw64 using structkeyValueStruct.

keyValueStruct.EncryptionKeyFile='encrypt.key'; keyValueStruct.RuntimeKeyLoaderFile='loader.mexw64'

The encryption key file must be in one of the following supported formats:

The MEX file loader retrieves the decryption key at runtime and must be an interface with the following arguments:

Avoid sharing the same key across multiple CTFs.

Example: 'ExternalEncryptionKey',keyValueStruct

Data Types: struct

Interface API, specified as one of the following options:

For more information, see Summary of MATLAB Compiler SDK C++ APIs.

Example: 'Interface','mwarray'

Name of the C++ shared library, specified as a character vector or a string scalar. The default name of the generated library is the first entry of theFunctionFiles argument.

Example: 'LibraryName','mymagic'

Data Types: char | string

Flag to obfuscate the deployable archive, specified as'on'/1/true or 'off'/0/false. The value is stored as an on/off logical value of type matlab.lang.onoffSwitchState.

If you set this property to 'on', then folder structures and file names in the deployable archive are obfuscated from the end user, and user code and data contained in .m,.mlapp, .p, .mat, MLX, SFX, and MEX files are placed into a user package within the archive. Additionally, all .m files are converted to P-files before packaging.

During runtime, MATLAB code and data is decrypted and loaded directly from the user package rather than extracted to the file system. MEX files are temporarily extracted from the user package before being loaded.

To manually include additional file types in the user package, add each file type in a separate extension tag to the file_`matlabroot`_/toolbox/compiler/advanced_package_supported_files.xml.

The following are not supported:

Enabling this option is equivalent to using mcc with-j and -s specified.

If you set this property to 'off', then the deployable archive is not obfuscated. This is the default behavior.

Example: 'ObfuscateArchive','on'

Data Types: logical

Path to the output directory where the build files are saved, specified as a character vector or a string scalar. The path can be relative to the current working directory or absolute.

The default name of the build folder is the library name appended withcppSharedLibrary.

Example: 'OutputDir','D:\Documents\MATLAB\work\mymagiccppSharedLibrary'

Data Types: char | string

MATLAB sample files used to generate sample C++ library files for functions included within the library, specified as a character vector, a string scalar, a string array, or a cell array of character vectors. Paths can be relative to the current working directory or absolute. Files must have a.m extension. For more information and limitations, seeCreate Sample Code to Call Exported Function.

Example: 'SampleGenerationFiles',["sample1.m","sample2.m"]

Data Types: char | string | cell

Since R2024b

Path to a secret manifest JSON file that specifies the secret keys to be embedded in the deployable archive, specified as a character vector or a string scalar. The path can be relative to the current working directory or absolute.

If your MATLAB code calls the getSecret, getSecretMetadata, or isSecret function, you must specify the secret keys to embed in the deployable archive in a JSON secret manifest file. If your code callsgetSecret and you do not specify theSecretsManifest option, MATLAB Compiler™ issues a warning and generates a template JSON file in the output folder named_`<componentname>`__secrets_manifest.json. Modify this file by specifying the secret key names in the Embedded field.

The setSecret function is not deployable. To embed secret keys in a deployable archive, you must call setSecret in MATLAB before you build the archive.

For more information on deployment using secrets, see Handle Sensitive Information in Deployed Applications.

Example: 'SecretsManifest','D:\Documents\MATLAB\work\mycomponent\mycomponent_secrets_manifest.json'

Data Types: char | string

Support packages to include, specified as one of the following options:

Example: 'SupportPackages',{'Deep Learning Toolbox Converter for TensorFlow Models','Deep Learning Toolbox Model for Places365-GoogLeNet Network'}

Data Types: char | string | cell

Flag to control build verbosity, specified as 'on' or'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent totrue, and 'off' is equivalent tofalse. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

Example: 'Verbose','on'

Data Types: logical

Output Arguments

collapse all

Build results, returned as a compiler.build.Results object. The Results object contains:

Version History

Introduced in R2021a

expand all

Use the ExternalEncryptionKey option to specify a 256-bit AES encryption key and a MEX-file loader interface to retrieve the decryption key at runtime. This option is equivalent to the mcc -k option.

Use the SecretsManifest option to include a JSON file that specifies secrets to embed within your deployable code archive. This option is equivalent to themcc -J option.

Use the ObfuscateArchive option to obfuscate folder structures and file names, and place MATLAB file data and user code into a user package within the archive. Additionally, all .m files are converted to P-files before packaging. This option is equivalent to using mcc with -j and-s specified.

Use the SupportPackages option to specify support packages to include in the deployable code archive.