C++中使用C语言-extern c

个人理解:extern "C"为什么引入?是因为可移植性,能在C++代码中使用C代码或在C代码中使用C++代码。我们都知道同一个普通的函数在C++编译器和C编译器编译后在符号库的名字是不同的。我们在C++代码中调用C函数的话,如果不用extern "C"的话,你调用这个函数的话,编译器是以C++的方式去查找,所以会提示未定义,必须用extern “C”的结构,指定调用的是C风格的函数,则会以C方式来查找,才能找到的。

以下是用法总结:

1.如何在C++代码中包含标准C头文件?

//C++ 代码
#include <cstdio>
using namespace std;
int main()
{
  printf("hello world !\n");
  return 0;
}



//使用C++编译器编译的C代码
#include <cstdio.h>
int main()
{
  printf("hello world !\n");
  return 0;
}




2.如何在C++代码中包含非系统C头文件

//pro.h 
void PrintMessage();
//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
  printf("hello world !\n");
}
//main.cpp
extern "C"
{
  #include "pro.h"//这个声明告诉C++编译器,包含进来的"pro.h"是C函数的头文件,即以C方式 #include "pro.h"
};
int main()
{
  PrintMesssge();
  return 0;
}



3.如何修改C头文件,以使之方便的被C++代码#include 

//pro.h 
//__cplusplus只存在于C++编译器下,注意cplusplus前面有两个下划线
#ifdef __cplusplus
extern "C"
{
#endif
   void PrintMessage();
#ifdef __cplusplus
};
#endif//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
  printf("hello world !\n");
}
 
//main.cpp
#include "pro.h"
int main()
{
PrintMessage();
  return 0;
}



4.如何在C++代码中调用非标准的C函数
//pro.h
void PrintMessage();
//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
  printf("hello world");
}
 
//main.cpp
extern "C" void PrintMessage();//这个声明告诉C++编译器,调用PrintMessage是以C的方式调用
int main()
{
  PrintMessage();
  return 0;
}



5.如何写出能够被C代码中调用的C++函数?

//pro.h
extern "C" void PrintMessage();//当知道一个C++函数会被C编译器调用时,可以使用extern “C” 结构来声明函数。
//pro.cpp
#include <iostream>
#include "pro.h"
void PrintMessage()
{
cout<<"hello world !"<<endl;
}
 
//main.c
extern void PrintMessage();
void main()
{
  PrintMessage();
}



6.如何修改C++头文件,以使之方便的被C代码#include
//pro.h
#ifdef __cplusplus
extern "C"
{
#endif
  void PrintMessage();
#ifdef __cplusplus
};
#endif
//pro.cpp
#include <iostream>
#include "pro.h"
void PrintMessage()
{
  cout<<"hello world !\n"<<endl;
}
 
//main.c
#include "pro.h"
void main()
{
  PrintMessage();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值