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

本文详细介绍了如何在C++中调用C语言的变量和函数,以及反过来在C中调用C++的函数。通过编译和链接过程的分析,解释了`extern "C"`在C++中的作用,以及在不同编译环境中如何确保兼容性。内容包括C++编译C代码、C编译C++代码以及最终的链接步骤。
摘要由CSDN通过智能技术生成

第一部分: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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值