- 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;
}
运行输出:
C++由于支持函数重载,编译后的函数名与C语言不同,导致直接调用C函数会出现链接错误。为解决此问题,可以使用extern "C"来告诉C++编译器按照C语言的方式处理函数,从而能够正确调用C语言的函数。这里通过一个VS2015的Win32控制台应用实例,展示了如何在C++中调用C函数的方法。

2147

被折叠的 条评论
为什么被折叠?



