标签:blog http io ar os sp on 2014 log
一 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
/************************************************************************* > 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; }
CC=gcc all: $(CC) -g -o main main.c test.cpp
二 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
/************************************************************************* > 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; }
/************************************************************************* > 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; }
CC=g++ all: $(CC) -g -o main main.cpp test.c test.h
标签:blog http io ar os sp on 2014 log
原文地址:http://blog.csdn.net/wangzhicheng1983/article/details/41018043