extern"C"的用法
在 C++ 程序中,可以使用 extern"C" 标注C语言代码,编译器会将 extern"C" 标注的代码以C语言的方式编译。
使用 extern"C" 标注C语言代码的格式具体如下:
使用 extern"C" 标注C语言代码的格式具体如下:
extern"C"
{
// C语言代码
}
1) mallocStr.h
#include<stdio.h> #include<stdlib.h> char* func(int,char*)
2) mallocStr.c
#define _CRT_SECURE_NO_WARNINGS #include"mallocStr.h" char* func(int size,char *str) { char* p =malloc(size); strcpy(p,str); return p; }
3) main.cpp
#include<iostream> using namespace std; #ifdef __cplusplus extern"C" { #endif #include"mallocStr.h" #ifdef __cplusplus } #endif int main() { char str[]="C++"; char *p=func(sizeof(str)+1,str); cout<<p<<endl; free (p); return 0; }运行结果:
C++
示例分析:- mallocStr.h 文件和 mallocStr.c 文件所示代码是C语言程序。其中,mallocStr.c 文件中定义了 func() 函数,在函数内部调用 malloc() 函数申请一块内存空间存储一个字符串。func() 函数第一个参数指定申请内存的大小,第二个参数是存入内存空间的字符串。
- main.cpp 中,程序调用了 func() 函数,则需要使用 extern"C" 声明 mallocStr.h 文件内容以C语言的方式编译。