首页 > 编程笔记

extern"C"的用法

在 C++ 程序中,可以使用 extern"C" 标注C语言代码,编译器会将 extern"C" 标注的代码以C语言的方式编译。

使用 extern"C" 标注C语言代码的格式具体如下:

extern"C"
{
    // C语言代码
}

下面通过案例演示在 C++ 程序中编译C语言程序,这个案例包括 mallocStr.h、mallocStr.c 和 main.cpp 三个文件,三个文件的实现分别如下所示。

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++

示例分析:

优秀文章