目录
一个C语言文件p.c
#include <stdio.h>
void print(int a,int b)
{
printf("这里调用的是C语言的函数:%d,%d\n",a,b);
}
一个头文件p.h
#ifndef _P_H
#define _P_H
void print(int a,int b);
#endif
C++文件调用C函数
#include <iostream>
using namespace std;
#include "p.h"
int main()
{
cout<<"现在调用C语言函数\n";
print(3,4);
return 0;
}
执行命令
gcc -c p.c
g++ -o main main.cpp p.o
编译后链接出错:main.cpp对print(int, int)未定义的引用。
修改p.h文件
#ifndef _P_H
#define _P_H
extern "C"{
void print(int a,int b);
}
#endif
修改后再次执行命令
gcc -c p.c
g++ -o main main.cpp p.o
./main
运行无报错
实验:定义main,c函数如下
#include <stdio.h>
#include "p.h"
int main()
{
printf("现在调用C语言函数\n");
print(3,4);
return 0;
}
重新执行命令如下
gcc -c p.c
gcc -o mian main.c p.o
报错:C语言里面没有extern “C“这种写法
为了使得p.c代码既能被C++调用又能被C调用
将p.h修改如下
#ifndef _P_H
#define _P_H
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
void print(int a,int b);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __P_H */
再次执行命令
gcc -c p.c
gcc -o mian main.c p.o
./mian
结果示意: