C++-函数:extern “C”【当在C++中调用C语言的方法时,利用extern “C”来解决C++编译后函数名与原始名称不一致的问题】

以下在Linux下测试:

c函数: void MyFunc(){} ,被编译成函数: MyFunc

c++函数: void MyFunc(){},被编译成函数: _Z6Myfuncv

通过这个测试,由于c++中需要支持函数重载,所以c和c++中对同一个函数经过编译后生成的函数名是不相同的,这就导致了一个问题,如果在c++中调用一个使用c语言编写模块中的某个函数,那么c++是根据c++的名称修饰方式来查找并链接这个函数,那么就会发生链接错误,以上例,c++中调用MyFunc函数,在链接阶段会去找Z6Myfuncv,结果是没有找到的,因为这个MyFunc函数是c语言编写的,生成的符号是MyFunc。

那么如果我想在c++调用c的函数怎么办?

extern "C"的主要作用就是为了实现c++代码能够调用其他c语言代码。加上extern "C"后,这部分代码编译器按c语言的方式进行编译链接,而不是按c++的方式。

MyModule.h

#ifndef MYMODULE_H

#define MYMODULE_H

#include<stdio.h>

#if __cplusplus

extern "C"{

#endif

    void func1();

    int func2(int a,int b);

#if __cplusplus

}

#endif

#endif

MyModule.c

#include"MyModule.h"

void func1(){

    printf("hello world!");

}

int func2(int a, int b){

    return a + b;

}

TestExternC.cpp

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>

using namespace std;

#if 0

    #ifdef __cplusplus

    extern "C" {

        #if 0

            void func1();

            int func2(int a, int b);

        #else

            #include"MyModule.h"

        #endif

    }

    #endif

#else

    extern "C" void func1();

    extern "C" int func2(int a, int b);

#endif

int main(){

    func1();

    cout << func2(10, 20) << endl;

    return EXIT_SUCCESS;

}

test.h

#pragma  once // 编译一次


#ifdef __cplusplus //两个_下划线(如果是在C++环境中使用该函数)
extern "C" {
#endif // !__cplusplus



#include <stdio.h>

	void show();



#ifdef __cplusplus //两个_下划线
}
#endif // !__cplusplus

test.c

#include "test.h"

void show()
{
	printf("hello world \n");
}

extern_c.cpp

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include "test.h"


//C++中想调用C语言方法

//extern "C" void show(); //show方法 按照C语言方式做连接
//解决的问题就是 在C++中调用C语言的函数

int main(){

	show(); //在C++中 函数是可以发生重载的,编译器会把这个函数名称偷偷改变  _showv  void

	system("pause");
	return EXIT_SUCCESS;
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值