版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
为什么要在c文件函数里调用c++文件函数?
很多现有代码都是c语言写的,我们需要对其进行扩展时,如果需要用到模板或类时,就需要使用c++编写,而且c++提供了STL,可以很方便的实现一些功能,所以使用c++编程可以减少工作量。
如何在c项目里编写c++文件代码?
- 将函数声明放在头文件中
- 把要被c函数调用的c++函数的声明放在
extern "C"{ ... }
语句块里 - 标准c++的头文件包含不能放在
extern "C"{ ... }
语句块里 - 示例:
test_c.c里的函数c_test()调用了test_cpp1.cpp文件里的函数cpp_test()。
//test_c.h
#ifndef TEST_C_H
#define TEST_C_H
void c_test(int *array,int n);
#endif
//test_c.c
#include "test_c.h"
#include "test_cpp1.hpp"
void c_test(int *array,int n){
for(int i=0;i<n;++i){
array[i]=i;
}
cpp_test(array,n);
}
test_cpp1.hpp里被test_c.c文件里c_test()函数调用的函数cpp_test()的声明需要放在extern "C"{ ... }
语句块里。
//test_cpp1.hpp
#ifndef TEST_CPP_1_HPP
#define TEST_CPP_1_HPP
#ifdef __cplusplus //-----------标准写法-----------
extern "C"{ //-----------标准写法-----------
#endif //-----------标准写法-----------
void cpp_test(int *array,int n); //要被c函数调用
#ifdef __cplusplus //-----------标准写法-----------
} //-----------标准写法-----------
#endif //-----------标准写法-----------
#endif
//test_cpp1.cpp
#include <vector>
#include <iostream>
#include "test_cpp1.hpp"
#include "test_cpp2.hpp"
using namespace std;
void test(){
cout<<"cpp test .\n"<<endl;
}
void cpp_test(int *array,int n){
vector<int> vec;
for(int i=0;i<n;++i){
array[i]*=2;
vec.push_back(array[i]);
}
test();
test1();
}
test_cpp1.cpp文件里函数调用了test_cpp2.cpp文件里的函数test1()。
//test_cpp2.hpp
#ifndef TEST_CPP_2_HPP
#define TEST_CPP_2_HPP
void test1();
#endif
//test_cpp2.cpp
#include <vector>
#include <iostream>
#include "test_cpp2.hpp"
using namespace std;
void test1(){
vector<int> vec;
vec.push_back(1);
cout<<"test1.\n"<<vec.front()<<endl;
}
最后主调文件main.c调用test_c.c文件里的函数。
#include <stdio.h>
#include <stdlib.h>
#include "test_c.h"
int main(){
int n=5;
int *array=(int *)calloc(n,sizeof(int));
c_test(array,n);
for(int i=0;i<n;i++){
printf("%d ",array[i]);
}
printf("\n");
return 0;
}
下面进行编译:
gcc -c test_c.c main.c
g++ -c test_cpp1.cpp test_cpp2.cpp -lstdc++
gcc -o main main.o test_c.o test_cpp1.o test_cpp2.o -lstdc++
可生成可执行文件main,中间文件main.o test_c.o test_cpp1.o test_cpp2.o。
运行main:
实现了c函数调用c++函数。