C与C++代码互相访问
2015-06-25 20:31
435 查看
1、C++代码中访问C语言变量或函数
首先在C语言的头文件(假设为_c.h)中,使用extern“C”{extern int a; extern int foo();},然后在C实现文件中正常定义,最后在C++文件中访问C语言变量或函数时,只需包含C语言头文件即可。如下代码所示:
2、C代码访问C++语言文件中变量或函数
首先在C++语言的头文件中加上extern“C” 声明变量或函数,如:extern “C” {extern int a; extern int foo();再在C++实现文件中定义。最后在C语言文件中访问变量a或函数foo时,只需在C的实现文件全局域中使用externint a;或extern int foo()声明。即可正常访问。代码如下所示:
首先在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; }
相关文章推荐
- 微软100题第46题:四对括号可以有多少种匹配排列方式?
- 北大百炼1006 Biorhythms 题解
- 北大百炼1005 I Think I Need a Houseboat题解
- 北大百炼1004 Financial Management 题解
- c++11 移动语意 gcc 实测
- 俄罗斯方块(C语言)
- C++ Primer 学习笔记_9_标准库类型(续3) -- biteset
- C++ Primer 学习笔记_8_标准库类型(续2) -- iterator
- C++ Primer 学习笔记_7_标准库类型(续1) -- vector类型
- 五子棋C语言实现
- 文件输入输出(C++)
- C语言--函数指针和回调函数
- C++ 运算符重载的注意点
- C++ Primer学习7:const iterator与const_iterator的区别
- C++ Primer快速学习 第一章 入门之二:输入与输出 (IO)
- C++ Primer学习6:const指针 和 指针与const限定符区别
- 更新代码和工具,组织起来,提供所有博文(C++,2014.09)
- C++ Primer学习5:vector使用下标操作元素注意
- C++ Primer 学习4:string类使用重载操作符+的注意
- error C4430: missing type specifier - int assumed. Note: C++ does not support default-int