C C++相互调用实例

一  C调用C++

1. 代码组织

2. test.h

/*************************************************************************
    > File Name: test.h
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 04:18:38 PM WST
 ************************************************************************/
#ifndef TEST_H
#define TEST_H
class CTest {
	private:
		int a, b;
	public:
		CTest(int, int);
		int Add();
};
#endif

3. test.cpp

/*************************************************************************
    > File Name: test.cpp
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 04:37:29 PM WST
 ************************************************************************/

#include "test.h"
CTest::CTest(int m, int n) {
	this->a = m;
	this->b = n;
}
int CTest::Add() {
	return this->a + this->b;
}
extern "C" {     // compile according C 
	int CAdd(int a, int b) {
		CTest test(a, b);
		return test.Add();
	}
}
4. main.c

/*************************************************************************
    > File Name: test.c
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 04:23:11 PM WST
 ************************************************************************/

#include <stdio.h>
extern int CAdd(int a, int b);
int main() {
	int n = CAdd(2, 6);
	printf("%d\n", n);

	return 0;
}

5. Makefile

CC=gcc
all:
	$(CC) -g -o main main.c test.cpp 

6. 测试


二 C++调C

1. 代码组织

2. test.h

/*************************************************************************
    > File Name: test.h
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 05:21:48 PM WST
 ************************************************************************/
#ifndef TEST_H
#define TEST_H
#ifdef _cplusplus
extern "C" {
#endif
	int add(int, int);   // C implement
#ifdef _cplusplus
}
#endif
#endif

3. test.c

/*************************************************************************
    > File Name: test.c
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 05:24:26 PM WST
 ************************************************************************/

#include <stdio.h>
#include "test.h"
int add(int a, int b) {
	return a + b;
}

4. main.cpp

/*************************************************************************
    > File Name: main.cpp
    > Author: ma6174
    > Mail: ma6174@163.com 
    > Created Time: Tue 11 Nov 2014 05:25:24 PM WST
 ************************************************************************/

#include <iostream>
#include "test.h"
using namespace std;
int main() {
	int n = add(2, 6);
	cout << n << endl;
	
	return 0;
}

5. Makefile

CC=g++
all:
	$(CC) -g -o main main.cpp test.c test.h

6. 测试


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值