C/C++(3)C++调用C语言的函数和头文件

C++由于支持函数重载,编译后的函数名与C语言不同,导致直接调用C函数会出现链接错误。为解决此问题,可以使用extern "C"来告诉C++编译器按照C语言的方式处理函数,从而能够正确调用C语言的函数。这里通过一个VS2015的Win32控制台应用实例,展示了如何在C++中调用C函数的方法。
  1. C++语言支持函数重载,C语言不支持函数重载。函数被C++编译后在库中的名字与C语言的不同,C++和C是两种完全不同的编译链接处理方式,如果直接在C++里面调用C函数,会找不到函数体,报链接错误,解决办法:加 extern “C”,示例如下:
    VS2015新建win32控制台应用程序,添加如下文件
    c_include.h:
#pragma once
#include <stdio.h>

int add(int x, int y);
int mul(int x, int y);

c_include.c:

#include "c_include.h"

int add(int x, int y) {
    printf("this is the function add in the c_include.h file\n");
    return x + y;
}

int mul(int x, int y){
    return x * y;
}

c_function.c:

#include <stdio.h>

int sub(int x, int y) {
    printf("this is function sub in c_function.c\n");
    return x - y;
}

int md(int x, int y) {
    return x % y;
}

main.c:

#include <iostream>
using namespace std;

//#include "c_include.h"        //引用C语言中的头文件这样是不行的
extern "C" {
    #include "c_include.h"
}

extern "C" {                    //引用C语言.c文件中的函数,不然main函数中的测试语句不能通过编译
    int sub(int, int);
    extern int md(int, int);
}
//#include "c_function.c"       //这样包含.c文件也可以

int main() {
    cout << "extern C #include add: " << add(2, 3) << endl;
    cout << "extern C #include mul: " << mul(2, 3) << endl;
    cout << "extern C sub: " << sub(2, 3) << endl;
    cout << "extern C md: " << md(2, 3) << endl;

    return 0;
}

运行输出:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值