c++和c混编

c主程序调用c++函数,如本示例中的init()。
c++函数中又访问c中的变量,如本示例中的infoget(),访问了c中的变量a。
c++函数中又访问c中的函数,如本示例中的testget(),调用了c中的geta()。

  • 概述
示例代码目录:
[root@localhost ccc]# tree
.
├── a.out
├── build.sh
├── foo.c
├── foo.h
├── main.c
├── num.c
└── rpc.cc

编译:
./build.sh

测试:
[root@localhost ccc]# ./a.out    
c main a_local[100]
c main geta[100]
c main seta to 5
c main a_local[5]
c main geta[5]

HelloWorld
cc info get 5
cc info set 5 to 600

cc get a 600
cc set a 2
c main a_local[2]
c main geta[2]

  • main.c
#include <stdio.h>

#include "foo.h"

extern int a;
extern void init();
extern void infoget();
extern void infoset(int);
extern void testset(int);
extern int testget();

int main()
{
        // call c 
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n", geta());
        printf("c main seta to 5\n", seta(5));
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n\n", geta());

        //call c++ val 
        init();
        infoget();
        infoset(600);
        printf("\n");

        //call c++ func 
        testget();
        testset(2);
        printf("c main a_local[%d]\n", a);
        printf("c main geta[%d]\n", geta());
}
  • foo.h
#ifdef __cplusplus
extern "C" {
#endif 

extern int a;

int geta();
int seta(int);

#ifdef __cplusplus  
}  
#endif

  • foo.c
#include "foo.h"


int geta() {
    return a;
}

int seta(int v) {
    a=v;
}
  • num.c
int a= 100;
#include <iostream>

#include "foo.h"

extern "C" int testget();
extern "C" void testset(int);
extern "C" void init();
extern "C" void infoget();
extern "C" void infoset(int);

using namespace std;

void infoget()
{
    cout << "cc info get ";
    cout << a << endl;
}

void infoset(int v)
{
    cout << "cc info set ";
    cout << a ;
    a = v;
    cout << " to ";
    cout << a  << endl;
}

int testget()
{
    int a;
    cout << "cc get a ";
    a = geta();
    cout << a << endl;
    return a;
}

void testset(int i)
{
    cout << "cc set a ";
    cout << i << endl;
    seta(i);
}

void init()
{
    cout << "HelloWorld" << endl;
}
#!/bin/sh
gcc main.c num.c foo.c rpc.cc  -lstdc++
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值