1. C++中调用C的函数
1.1 在.cpp中extern "C"
告知编译器:这几个函数此处使用C方式编译。
这就和.c中编译生成的函数名相同了。
//类型1
extern "C" void foo(int x, int y);
//类型2
extern "C"{
int foo(int x, int y);
void bar();
}
//方法3
extern "C" {
#include “myheader.h”
}
1.2 在.c中extern "C"
直接加是不行的,C中并不支持extern "C"
,所以要加上ifdef __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
void DeleteStack(Stack stack);
void PrintStack(Stack stack);
void Pop(Stack stack);
#ifdef __cplusplus
}
#endif
2. C中调用C++的函数
2.1 普通非成员函数
2.1.1 在C++的.h中extern "C"
// 也可添加ifdef __cplusplus
extern "C" void PrintCpp(void);
extern "C"{
int foo(int x, int y);
void bar();
}
此时.c中可直接使用。
但直接报告该头文件可能会由于其他一些文件问题导致出错,所以建议在需要的.c文件中只extetn 需要的函数。
2.3 C++特有的全局变量
类似于vector的全局变量定义在.cpp中。
需要把对这些变量的操作或读取封装为函数。
#include "C++.h"
map<int, string> g_keyvalue;
void C_g_keyvalueInsert()
{
g_keyvalue.insert(pair(1, "srdfg"));
}
#ifndef _C++.H_
#define _C++.H_
extern "C" void C_g_keyvalueInsert();
#endif
extern void C_g_keyvalueInsert();
#就可以使用了,无需引入全局变量。