为什么C++中能函数重载而C不可以
test.c
#include <stdio.h>void fun(){} void fun1(int a){}int main(){return 0;}
test.c汇编代码
test.cpp
#include<iostream>using namespace std;void fun(){} void fun(int a){}int main(){return 0;}
test.cpp汇编代码
C++编译函数方法是 使用mangle的技术,对函数重载的函数名加上编译器中自定义规则的表示符,编译之后的函数名就会不一样,例如
fun()----->_Z3funv fun(int a)------>_Z3funi
如果想在C++程序中调用C语言编写的API,就要使用extern “C”
extern “C” 用法
1、直接在函数前加 extern “C”
extern "C" void fun() {printf("test");}
2、如果函数有声明和实现两部分,则在声明时加 extern “C”
extern "C" void func();void func() {cout << "func" << endl ;}
3、如果存在多个函数声明需要加 extern “C”,可以用{}包围
extern "C" {void func();void func1();}void func() {cout << "func()" << endl;}void func1() {cout << "func1()" << endl;}
自定义C语言函数库
通过在编写C函数库时 使用 extern "C"和 条件编译指令 ,我们可以编写在C和C++中都能使用的API
//TEST.h文件声明#ifndef __TEST_H#define __TEST_H#ifdef __cplusplus//__cplusplus是C++中特有的宏,用来判断是为C++调用extern "C" {#endifint sum(int a, int b);#ifdef __cplusplus}#endif#endif//TEST.c文件实现#include "TEST.h"int sum(int a, int b) {return a + b;}
__cplusplus这个宏是C++中 特有的 。它在加载C++文件的时候 会提前定义这个宏 ,所以我们只要 判断文件中是否有这个宏 ,有的话就是C++在调用,没有的话就是C语言,这样就可以很好地解决了这个混合调用的问题。