如果我想在C文件中实现某些功能,在CPP文件实现对这些功能的调用,我该如何做呢?
先将程序贴出来,然后在分析:
- // 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];
- // function
- int* func(int n);
- #ifdef __cplusplus
- }
- #endif
- #endif
- //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));
- }
- // 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编译:
- gcc -c -I. inct.c
此编译将会输出:inct.o
执行过程分析:gcc编译时,并没有预先定义__cplusplus这个宏,所以extern "C"并没有有效,inct.h被作为一般的C程序编译成功。
2、将test.cpp用C++编译器编译:
- g++ -c -I. test.cpp
输出 test.o
g++中定义了__cplusplus,所以,test.cpp中对inct.h中所有功能引用都添加了extern “C”,这样一来,c++中的程序引用.h中的东西时,就将他们看成由C编译器编译成的程序了。编译也没有问题。
3、将所有编译中间结果链接起来
- g++ test.o inct.o -o test
第二部分:C中调用C++的函数或变量
先贴代码:
inct.h的内容没有改变。
将inct.c改为inct.cpp,并且修改下程序内容:
- //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[n]); // 使用了new
- //return (int*)malloc(n*sizeof(int));
- }
将test.cpp修改为test.c,内容改变为:
- // 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编译:
- g++ -c -I. inct.cpp
此编译将会输出:inct.o
执行过程分析:g++编译时,预先定义__cplusplus这个宏,所以extern "C"有效,inct.h被作为一般的C++程序编译成功,但是编译后的变量和函数可以在C或C++程序中使用。
2、将test.c用C编译器编译:
- gcc -c -I. test.c
输出 test.o
gcc中没定义__cplusplus,所以,test.c中对inct.h中所有功能引用都没添加了extern “C”,这样一来,C语言程序正常引用这些函数或变量。
特别注意 extern "C"是C++中才有的,在C中只有extern,用在变量前,表示变量的声明,不表示变量的定义。
3、将所有编译中间结果链接起来
- g++ test.o inct.o -o test
- gcc test.o inct.o -o test -lstdc++