Why do I get "undefined reference" error when trying to generate code that references a C++ function?

4 visualizaciones (últimos 30 días)

I am trying to include a C++ function in my MATLAB code for code generation, and I have included the following lines, where the function "func" is defined in "function.h".

coder.cinclude('function.h');
coder.ceval('func');
However, I am getting an error:

undefined reference to `func'
Why does this happen, and how can I resolve this?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 17 de Jun. de 2025
Since the definition of the external function is defined in a C++ file, a C++ compiler will be used to build the object for that file.
By default, MATLAB Coder generates C code, and the generated C code will be calling into a C++ function. For C++ functions to be visible in C code, they must be exported with extern "C" attribute. The following is an example of this:
#ifndef _CPP_TEST_FN_H
#define _CPP_TEST_FN_H
#ifdef __cplusplus
extern "C" {
#endif
int mytestadd(int a, int c);
#ifdef __cplusplus
}
#endif
#endif
Alternatively, if you want the generated code in C++, you can use "-lang:C++" as an option to codegen command. In this case, the functions do not need to be exported using extern “C” attribute and generated code should successfully build.

Más respuestas (0)

Categorías

Más información sobre MATLAB Coder en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by