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

2 views (last 30 days)

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?

Accepted Answer

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

More Answers (0)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!