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

C++与C变量或函数的混合调用

2015-05-20 18:04 357 查看
第一部分:C++调用C变量或函数

如果我想在C文件中实现某些功能,在CPP文件实现对这些功能的调用,我该如何做呢?

先将程序贴出来,然后在分析:

[cpp]
view plaincopy

// file name : inct.h
#ifndef _INCT_H_
#define _INCT_H_

#define NUM 8

#ifdef __cplusplus
extern "C" {
#endif

// global C
extern int g_data[4][NUM];
/////c中的全局变量

// function
int* func(int n); /////c中的函数

#ifdef __cplusplus
}
#endif

#endif

[cpp]
view plaincopy

//file name : inct.c
#include "inct.h"
#include <stdlib.h>
#include <stdio.h>

int g_data[4][NUM]= \
{ \
{ 0, 0, 0, 64, 0, 0, 0, 0 },\
{ -1, 4, -10, 58, 17, -5, 1, 0 },\
{ -1, 4, -11, 40, 40, -11, 4, -1 },\
{ 0, 1, -5, 17, 58, -10, 4, -1 }\
};\

int* func(int n)
{
printf("your input is %d.\n", n);
return (int*)malloc(n*sizeof(int));
}

[cpp]
view plaincopy

// file name : test.cpp
#include <iostream>
#include <string>
#include <cstring>
#include "inct.h"
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main(int argc, char **argv)
{
int n=NUM;
int *data = func(n);
for (int i = 0; i < n; i++)
{
data[i] = g_data[2][i];
printf("data[%d]=%4d\n", i, data[i]);
}

free(data);

return 0;
}

我将这样编译:

1、首先将inct.c编译:

[cpp]
view plaincopy

gcc -c -I. inct.c

此编译将会输出:inct.o
执行过程分析:gcc编译时,并没有预先定义__cplusplus这个宏,所以extern "C"并没有有效,inct.h被作为一般的C程序编译成功。

2、将test.cpp用C++编译器编译:

[cpp]
view plaincopy

g++ -c -I. test.cpp

输出 test.o
g++中定义了__cplusplus,所以,test.cpp中对inct.h中所有功能引用都添加了extern “C”,这样一来,c++中的程序引用.h中的东西时,就将他们看成由C编译器编译成的程序了。编译也没有问题。

3、将所有编译中间结果链接起来

[cpp]
view plaincopy

g++ test.o inct.o -o test

第二部分:C中调用C++的函数或变量

先贴代码:

inct.h的内容没有改变。

将inct.c改为inct.cpp,并且修改下程序内容:

[cpp]
view plaincopy

//file name : inct.c
#include "inct.h"
#include <iostream>
using namespace std; //使用std命名空间

int g_data[4][NUM]= \
{ \
{ 0, 0, 0, 64, 0, 0, 0, 0 },\
{ -1, 4, -10, 58, 17, -5, 1, 0 },\
{ -1, 4, -11, 40, 40, -11, 4, -1 },\
{ 0, 1, -5, 17, 58, -10, 4, -1 }\
};\

int* func(int n)
{
cout << "your input is " << n << endl; //使用了cout
return (new int
); // 使用了new
//return (int*)malloc(n*sizeof(int));
}

将test.cpp修改为test.c,内容改变为:

[cpp]
view plaincopy

// file name : test.c
#include "inct.h"
#include <stdlib.h>
#include <stdio.h> //嫣然都是C的头文件

int main(int argc, char **argv)
{
int n=NUM;
int *data = func(n);
int i; //将i的声明拿出来了,C的语法
for (i = 0; i < n; i++)
{
data[i] = g_data[2][i];
printf("data[%d]=%4d\n", i, data[i]); 继续使用printf,来自C的接口
}

free(data); //将new来的数据free掉
return 0;
}

这样编译:

1、首先将inct.cpp编译:

[cpp]
view plaincopy

g++ -c -I. inct.cpp

此编译将会输出:inct.o

执行过程分析:g++编译时,预先定义__cplusplus这个宏,所以extern "C"有效,inct.h被作为一般的C++程序编译成功,但是编译后的变量和函数可以在C或C++程序中使用。

2、将test.c用C编译器编译:

[cpp]
view plaincopy

gcc -c -I. test.c

输出 test.o

gcc中没定义__cplusplus,所以,test.c中对inct.h中所有功能引用都没添加了extern “C”,这样一来,C语言程序正常引用这些函数或变量。

特别注意 extern "C"是C++中才有的,在C中只有extern,用在变量前,表示变量的声明,不表示变量的定义。

3、将所有编译中间结果链接起来

[cpp]
view plaincopy

g++ test.o inct.o -o test

或者

[cpp]
view plaincopy

gcc test.o inct.o -o test -lstdc++
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: