写程序时经常会遇到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<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
extern "C" {
#endif
c编程和c++编程。
/**** some declaration or so *****/
c++与c#、
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
example :首先假设有下面这样三个文件:
c语言汇编混合编程意义,
/* file: test_extern_c.h */
#ifndef __TEST_EXTERN_C_H__
matlab与c语言混合编程方法,
#define __TEST_EXTERN_C_H__
#ifdef __cplusplus
c和vb。
extern "C" {
#endif
c加加调用python。
/*
* 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 <stdio.h>
#include <stdlib.h>
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++头文件 cppExample.h
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
extern "C" int add( int x, int y );
#endif
//C++实现文件 cppExample.cpp
#include "cppExample.h"
int add( int x, int y )
{
return x + y;
}
/* C实现文件 cFile.c
/* 这样会编译出错:#include "cExample.h" */
extern int add( int x, int y );
int main( int argc, char* argv[] )
{
add( 2, 3 );
return 0;
}
note: 如果 cppEample.h 改成:
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
#ifdef __cplusplus
extern "C" {
#endif
int add( int x, int y );
#ifdef __cplusplus
}
#endif
#endif
则在 C 文件中 #include "cExample.h" 就不会报错了.
总之, 无论写 c 还是 c++头文件,只要是想以后混合编程,就最好加上
#ifdef __cplusplus
extern "C" {
#endif
/**** some declaration or so *****/
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
可以增强代码的可移植性.