解决方案
这里以linux操作系统作为说明。
C调用C++的函数;
C++调用C的函数;
C调用C++的函数
base.h, C++的头文件
#ifdef __cplusplus //has c++ code
extern "C" { // 声明 C调用约定的函数
#endif
int addFunc(int a, int b); // declare func
#ifdef __cplusplus
}
#endif
base.cpp,C++的源码
#include "base.h" // 包含头文件
#include <iostream>
using namespace std;
// define function
int addFunc(int a, int b){
cout << "cpp func 'addFunc' running..." << a + b << endl;
return 0;
}
main.c, C源码
#include <stdio.h>
#include "base.h"
int main(){
printf("c to call cpp...\n");
int a, b;
a = 10;
b = 20;
// call cpp func
addFunc(a, b);
return 0;
}
开始编译:
[laufing@centos ttc]$ g++ -c base.cpp -I.
[laufing@centos ttc]$ ls
base.cpp base.h base.o main.c
[laufing@centos ttc]$ gcc main.c base.o -o app.out -lstdc++
[laufing@centos ttc]$ ls
app.out base.cpp base.h base.o main.c
[laufing@centos ttc]$ ./app.out
c to call cpp...
cpp func 'addFunc' running...30
C++ 调用C的函数
myc.h, C的头文件
#ifndef _MYC_H_ // 防止头文件被重复引入
#define _MYC_H_
//declare
int getName(const char* name);
#endif
myc.c, C的源码
#include <stdio.h>
#include "myc.h"
// define
int getName(const char* name){
printf("c func is running...\n");
printf("current user name: %s\n", name);
printf("c func end.\n");
return 0;
}
main.cpp, C++的源码
#include <iostream>
using namespace std;
// declare extern "C"
extern "C" {
//int getName(char* name);
int getName(const char* name); // C++中必须为常量字符指针
}
int main(){
const char* name = "jack"; // must be const
getName(name);
return 0;
}
编译:
[laufing@centos ttc]$ gcc -c myc.c -I.
[laufing@centos ttc]$ ls
main.cpp myc.c myc.h myc.o
[laufing@centos ttc]$ g++ main.cpp myc.o -o app.out
[laufing@centos ttc]$ ls
app.out main.cpp myc.c myc.h myc.o
[laufing@centos ttc]$ ./app.out
c func is running...
current user name: jack
c func end.
C调用C++的类
MyClass.h
#pragma once
class Dog{ // 定义类
public:
Dog(); // 声明构造方法
void run(int a, int b); // 声明方法
};
MyClass.cpp
#include "MyClass.h"
#include "MyC.h"
#include <iostream>
using namespace std;
// 为C++ 定义 类的成员方法
Dog::Dog() {
//
}
void Dog::run(int a, int b) { // 定义类中 的 成员方法
cout << "i am a dog, i am running..." << endl;
cout << a + b << endl;
}
// 为C 定义方法
void* create_obj() {
return new Dog();
}
void destroy_obj(void* obj) {
delete static_cast<Dog*>(obj);
}
void call_run(void* obj, int a, int b) {
return static_cast<Dog*>(obj)->run(a, b);
}
MyC.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void* create_obj();
void destroy_obj(void* obj);
void call_run(void* obj, int a, int b);
#ifdef __cplusplus
}
#endif // _cplusplus
main.c
#include "MyC.h"
#include <stdio.h>
int main() {
// 使用 C++的类 创建对象
void* dog = create_obj();
call_run(dog, 3, 7);
destroy_obj(dog);
return 0;
}
VC中成功运行,手动编译:
- cpp 代码编译为dll/so动态库;
- 编译c代码时,连接cpp的动态库;
- -L参数指定库的目录;
- -l指定目录下的库名,lib库名.dll
- -I 大i,指定自定义的头文件目录