Why do I get "undefined reference" error when trying to generate code that references a C++ function?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 17 Jun. 2025
Beantwortet: MathWorks Support Team
am 30 Jun. 2025
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?
Akzeptierte Antwort
MathWorks Support Team
am 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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu MATLAB Coder finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!