How to use C api in C++ ?
C++ 可以引用其他 C語言寫的 api,這不意外。
但要怎麼做?
C++:
請在把要使用的 C api 的 header 用 extern “C” 包起來
extern "C"
{
#include "demo_c_api_A.h"
#include "demo_c_api_B.h"
}
而要被使用的 C api 的 header:
demo_c_api_A.h:
#ifndef DEMO_C_API_A_H
#define DEMO_C_API_A_H
#include "aaa.h"
#include <bbb.h>
#ifdef __cplusplus
extern "C"
{
#endif
...
(C 的 header 原本該寫的東西)
...
#ifdef __cplusplus
}
#endif
#endif
你也可以不要直接用 extern 標全部,單獨寫:
#ifndef DEMO_C_API_A_H
#define DEMO_C_API_A_H
#include "aaa.h"
#include <bbb.h>
extern int c_api_A_init();
(C 的 header 原本該寫的東西)
#endif
#endif
延伸:extern 是什麼?
Last modified 1yr ago