c/c++混合编程(转)

原文地址:http://mashuai.blog.51cto.com/700343/167612

写程序时经常会遇到C++调用C库以及 C调用C++库的情况,也就是C, C++混合编程的问题.
   由于C和C++编译器对函数解析不同,今天用空专门对这个问提小结了一下.
主要参考了以下文章, 很多内容也是直接copy 过来的:
1. 静云谷 关于extern "C":
http://blog.chinaunix.net/u/270/showart_209504.html
2. 探索C++的秘密之详解extern "C" http://tech.163.com/06/0118/09/27O66HCC0009159Q.html
3. C++中extern “C”含义深层探索:
http://www.cppblog.com/Macaulish/archive/2008/06/17/53689.html
C++ 调用 C 函数:
这种情况相对简单,有两种方法:
1.  在标准 C 头文件里加入以下 code, c++ link 的时候就会知道要link C格式的函数.
#ifdef  __cplusplus
extern "C" {
#endif
/**** some declaration or so *****/
#ifdef  __cplusplus
    }
#endif  /* end of __cplusplus */
example :首先假设有下面这样三个文件:
/* file: test_extern_c.h */
#ifndef __TEST_EXTERN_C_H__
#define __TEST_EXTERN_C_H__
#ifdef  __cplusplus
extern "C" {
#endif
/*
* this is a test function, which calculate
* the multiply of a and b.
*/
extern int ThisIsTest(int a, int b);
#ifdef  __cplusplus
    }
#endif  /* end of __cplusplus */
#endif
在这个头文件中只定义了一个函数,ThisIsTest()。这个函数被定义为一个外部函数,可以被包括到其它程序文件中。假设ThisIsTest()函数的实现位于test_extern_c.c文件中:
/* test_extern_c.c */
#include "test_extern_c.h"
int
ThisIsTest(int a, int b)
{
    return (a + b);
}
可以看到,ThisIsTest()函数的实现非常简单,就是将两个参数的相加结果返回而已。现在,假设要从CPP中调用ThisIsTest()函数:
/* main.cpp */
#include "test_extern_c.h"
#include
#include
class FOO {
    public:
        int bar(int a, int b)
        {
            printf("result=%i/n", ThisIsTest(a, b));
        }
};
int
main(int argc, char **argv)
{
    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
    FOO *foo = new FOO();
    foo->bar(a, b);
    return(0);
}
在这个CPP源文件中,定义了一个简单的类FOO,在其成员函数bar()中调用了ThisIsTest()函数。下面看一下如果采用gcc编译test_extern_c.c,而采用g++编译main.cpp并与test_extern_c.o连接会发生什么情况:
[cyc@cyc src]$ gcc -c test_extern_c.c
[cyc@cyc src]$ g++ main.cpp test_extern_c.o
[cyc@cyc src]$ ./a.out 4 5               
result=9
2. 直接在c++文件中这样引用c 头文件:
extern "C"
{
#include "f.h"
}
C 调用 C++ 函数:
在标准 C++ 头文件里加入以下 code, c++ link 的时候就会知道要link C格式的函数.
#ifdef  __cplusplus
extern "C" {
#endif
/**** some declaration or so *****/
#ifdef  __cplusplus
    }
#endif  /* end of __cplusplus */
example1:
//C++头文件 cppExaIC8qI

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值