- 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:
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;
extern "C" {
#include "c_include.h"
}
extern "C" {
int sub(int, int);
extern int md(int, int);
}
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;
}
运行输出:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)