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

2 次查看(过去 30 天)

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?

采纳的回答

MathWorks Support Team
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by