C調用C++鏈接庫
C調用C++鏈接庫:
1.編寫C++代碼,編寫函數的時候,需要加入對C的接口,也就是extern “c"
2.由於C不能直接用"class.function”的形式調用函數,所以C++中需要為C寫一個接口函數。例如本來要調用student類的talk函數,就另外寫一個cfun(),專門建一個student類,並調用talk函數。而cfun()要有extern聲明
3.我在練習中就使用在C++頭文件中加extern ”c”的方法。而C文件要只需要加入對cpp.h的引用
4.詳細見如下代碼:
student是一個類,里邊有talk函數,就輸出一句話而已
cpp.cpp與cpp.h是兩個C++代碼,包含對C的接口
最后用C代碼:helloC.c來測試結果
student.cpp:
1
#include
<
iostream
>
2
using
namespace
std;
3
#include
"
student.h
"
4
void
student::talk()
{
5
cout<<"I am Kenko"<<endl;
6
}
7
8
9
#include
<
iostream
>
2
using
namespace
std;3
#include
"
student.h
"
4
void
student::talk()
{5
cout<<"I am Kenko"<<endl;6
}
7

8

9
student.h:
1
#ifndef _STUDENT_
2
#define
_STUDENT_
3
4
class
student
{
5
public:
6
void talk();
7
}
;
8
9
#endif
#ifndef _STUDENT_2
#define
_STUDENT_
3

4
class
student
{5
public:6
void talk();7
}
;8

9
#endif
cpp.h:
1
#ifndef _CPP_
2
#define
_CPP_
3
4
#include
"
student.h
"
5
#ifdef __cplusplus
6
extern
"
C
"
{
7
#endif
8
void helloCplusplus();
9
#ifdef __cplusplus
10
}
11
#endif
12
13
#endif
#ifndef _CPP_2
#define
_CPP_
3

4
#include
"
student.h
"
5
#ifdef __cplusplus6
extern
"
C
"
{7
#endif8
void helloCplusplus();9
#ifdef __cplusplus10
}
11
#endif
12

13
#endif
cpp.cpp:
1
#include
<
iostream
>
2
using
namespace
std;
3
4
#include
"
cpp.h
"
5
student stu;
6
void
helloCplusplus()
{
7
cout<<"helloC++"<<endl;
8
stu.talk();
9
}
10
11
void
helloCplusplus2()
{
12
cout<<"helloC++"<<endl;
13
}
#include
<
iostream
>
2
using
namespace
std;3

4
#include
"
cpp.h
"
5
student stu;6
void
helloCplusplus()
{7
cout<<"helloC++"<<endl;8
stu.talk();9
}
10

11
void
helloCplusplus2()
{12
cout<<"helloC++"<<endl;13
}
helloC.c:
#include
<
stdio.h
>
#include " cpp.h "
int main(){
helloCplusplus();
return 0 ;
}
#include " cpp.h "
int main(){
helloCplusplus();
return 0 ;
}
我這次練習是直接在xp環境下,在CMD命令行方式用gcc,g++來編譯的。
1.編譯C++代碼,成為鏈接庫
g++ -shared -o libccall.so cpp.cpp student.cpp (libccall.so為庫名)
2.編譯C代碼:g++ helloC.c ./libccall.so。這里一定要用g++,如果用gcc會出錯,因為gcc編譯C++文件才會自動調用g++,但如果對象直接就是C文件就不會調用g++了。
在編譯的時候,使用g++進行編譯一般不會出現問題,但是如果使用gcc進行編譯的時候回出現許多未定義方法錯誤,因為gcc無法自動調用C++的
標准
庫,所以需要使用-lstdc++手動引用。

