本實(shí)例是最簡(jiǎn)化的實(shí)現(xiàn)模板钧栖,一個(gè)頭文件hello.h及其C++實(shí)現(xiàn)hello.cpp攀操,另外就是C代碼main.c针余,來(lái)調(diào)用hello.cpp實(shí)現(xiàn)的函數(shù).
hello.h
#ifndef H_HELLO
#define H_HELLO
#ifdef __cplusplus
extern "C" {
#endif
int getAge();
int getCount();
#ifdef __cplusplus
}
#endif
#endif
hello.cpp
#include <iostream>
#include "hello.h"
int getAge() {
std::cout << "get age" << std::endl;
return 99;
}
int getCount() {
std::cout << "get count" << std::endl;
return 123456;
}
編譯為動(dòng)態(tài)鏈接庫(kù)
g++ -fPIC -shared -o libhello.so hello.cpp
main.c
include <stdio.h>
#include "hello.h"
int main() {
int age = getAge();
int count = getCount();
printf("%d:%d\n", age, count);
return 0;
}
gcc main.c -L. -lhello -o main
makefile自動(dòng)化
main: main.c libhello.so
gcc main.c -L. -lhello -o main
libhello.so: hello.cpp
g++ -fPIC -shared -o libhello.so hello.cpp
clean:
rm -f *.o *.so main
至此葱绒,已經(jīng)實(shí)現(xiàn)了C代碼調(diào)用C++自定義庫(kù)函數(shù)
驗(yàn)證混合調(diào)用
main.cpp
#include <iostream>
#include "hello.h"
int main() {
int age = getAge();
std::cout << age << ":" << getCount() << std::endl;
return 0;
}
g++ main.cpp -L. -lhello -o main
可以看出绍在,C++门扇、C代碼可以共享函數(shù)getAge(), getCount()
注意事項(xiàng)
- __cplusplus前面是兩個(gè)下劃線(xiàn)
如果對(duì)你有一點(diǎn)幫助,麻煩為我點(diǎn)一個(gè)贊偿渡,如果沒(méi)有幫助臼寄,也非常期待你的反饋