一 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. 测试