Why do I get "undefined reference" error when trying to generate code that references a C++ function?
2 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2025-6-17
回答: MathWorks Support Team
2025-6-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
2025-6-17
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 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!