1、C++代码中访问C语言变量或函数
首先在C语言的头文件(假设为_c.h)中,使用extern“C”{extern int a; extern int foo();},然后在C实现文件中正常定义,最后在C++文件中访问C语言变量或函数时,只需包含C语言头文件即可。如下代码所示:
//_c.h
#ifdef __cplusplus
extern "C"
{
extern int a;
extern int foo();
}
#endif
_c.c
#include "my.h"
#include <stdio.h>
int a = 100;
int foo()
{
//printf("a =%d\n",a);
return 0;
}
//other.cpp
#include <iostream>
#include "my.h"
int main(int argc, char *argv[]) {
std::cout << a << std::endl;
foo();
return 0;
}
2、C代码访问C++语言文件中变量或函数
首先在C++语言的头文件中加上extern“C” 声明变量或函数,如:extern “C” {extern int a; extern int foo();再在C++实现文件中定义。最后在C语言文件中访问变量a或函数foo时,只需在C的实现文件全局域中使用externint a;或extern int foo()声明。即可正常访问。代码如下所示:
_cpp.h
extern "C"
{
extern int a;
extern int foo();
}
_cpp.cpp
#include "my.h"
int a = 88;
int foo()
{
return 0;
}
_main.c
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
extern int a;
extern int foo();
int main(int argc, char *argv[]) {
printf("a=%d\n",a);
foo();
return 0;
}