第一部分:C++调用C变量或函数
如果我想在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]