フィルターのクリア

How to call a function in C++ from library(.so) created by code generation?

4 ビュー (過去 30 日間)
Hyunjun Hyung
Hyunjun Hyung 2021 年 4 月 14 日
編集済み: Infinite_king 2024 年 4 月 17 日
Hello, all.
I created a .so file by selecting the ert_shrlib.tlc option during the code generation.
This option sets the target language to C.
Anyway, I want to use this library in Cpp.
However, it is very difficult to use the library because of the difference between C and Cpp.
Does anyone know how to use libraries(.so) based on C in Cpp?

回答 (1 件)

Infinite_king
Infinite_king 2024 年 4 月 17 日
編集済み: Infinite_king 2024 年 4 月 17 日
Hi Hyunjun Hyung,
The C library can be used by a C++ program. In fact, many OS libraries are written in C. Therefore, whenever a system call is made by a C++ program, it is actually utilizing a C library.
However, to use a C library, C linkage should be used to link the C functions. In your C++ code, declare the functions from the C library as extern "C". This instructs the C++ compiler to use C linkage for those functions, preventing name mangling and ensuring compatibility with the C library.
Ideally, the header file should include the extern "C" keyword. If the header file does not contain this keyword, update the function declarations as follows
// Shift the function declaration inside the extern "C" scope
extern "C" {
void doSomething();
}
Finally, link the library while compiling as follows,
% linking library named 'my_library.so'
g++ .. -lmy_library -L/custom_directory_path

カテゴリ

Help Center および File ExchangeDeployment, Integration, and Supported Hardware についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by