您的位置:首页 > 编程语言 > C语言/C++

【六】C & C++ 函数相互调用

2015-08-15 16:54 706 查看

目录

目录
1C调用C编写的函数

2C调用C编写的函数

3统一的解决方案

4注意

  在项目中融合C++和C代码是实际工程中不可避免的,虽然C++编译器能够兼容C语言的编译方式,但C++编译器会优先使用C++的方式进行编译,为了让它们能互相调用,可以利用extern关键字强制让C++编译器对代码进行C方式编译!

1、C++调用C编写的函数

假设有如下的代码:

main.cpp

#include <iostream>
#include "test.h"

using namespace std;

int main(int argc, char *argv[])
{
cout << "add =" << add(5, 5) << endl; //add函数由C语言编写,并由gcc按C语言方式编译
return 0;
}


test.h

#ifndef _TEST_H_
#define _TEST_H_

int add(int a, int b);

#endif


test.c

#include "test.h"

int add(int a, int b)
{
return a + b;
}


首先,我们使用gcc编译器,对test.c进行编译,生成test.o文件,然后供main.cpp使用!

gcc -Wall -g -c test.c


然后,使用g++编译main.cpp

g++ -Wall -g main.cpp test.o -o main


这时会看到编译器报错:



改正方法:

将main.cpp改为如下:

#include <iostream>

//告诉编译器,test.h头文件中所有函数是C语言编译出来的
extern "C"
{
#include "test.h"
}

using namespace std;

int main(int argc, char *argv[])
{
cout << "add =" << add(5, 5) << endl;
return 0;
}


再试着编译,就能通过了!

2、C调用C++编写的函数

假设有如下的代码:

main.c

#include <stdio.h>
#include "test.h"

int main()
{
printf("add = %d\n", add(1,2)); //add函数由C++编写
return 0;
}


test.h

#ifndef _TEST_H_
#define _TEST_H_

int add(int a, int b);

#endif


test.cpp

#include "test.h"

int add(int a, int b)
{
return a+b;
}


首先,我们使用g++编译器,对test.cpp进行编译,生成test.o文件,然后供main.c使用!

编译命令:

g++ -Wall -g -c test.cpp


然后,使用gcc编译器,编译main.c:

gcc -Wall -g main.c test.o -o main


可以看到,这里编译器会报错:



改正方法:

在test.cpp中改成如下内容,让g++采用C的编译方式对它进行编译:

extern "C"
{
#include "test_1.h"

int add(int a, int b)
{
return a+b;
}

}


再次编译,就不会出错了!

3、统一的解决方案

__cplusplus是C++编译器内置的标准宏定义

__cplusplus的意义

让C代码即可以通过C编译器的编译,也可以在C++编译器中以C方式编译

因此,我们通常在要把C++函数库链接到C程序中时,在C++源代码中做如下的定义:

#ifdef __cplusplus
extern "C" {
#endif

//函数声明 或 函数定义

#ifdef __cplusplus
}
#endif


这样,g++编译器会自动以C的方式编译该代码!

4、注意

C++编译器不能以C的方式编译多个重载函数!

原因很简单,C语言中不支持函数重载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: