Chinaunix首页 | 论坛 | 博客
  • 博客访问: 18397
  • 博文数量: 12
  • 博客积分: 266
  • 博客等级: 二等列兵
  • 技术积分: 110
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-07 10:14
文章分类

全部博文(12)

文章存档

2012年(4)

2011年(8)

我的朋友

分类: C/C++

2011-05-18 11:07:18

Calling C from C++
The following example is a C++ program that calls a C function named csayhello().
This call can be made directly because the function is declared in the C++ program as
extern "C":

/* cpp2c.cpp */
#include
extern "C" void csayhello(char *str);
int main(int argc,char *argv[])
{
csayhello("Hello from cpp to c");
return(0);
}
The C function requires no special declaration and appears as follows:
/* csayhello.c */
#include
void csayhello(char *str)
{
printf("%s\n",str);
}
The following three commands compile the two programs and link them into an
executable. The flexibility of g++ and gcc allow this to be done in different ways, but
this set of commands is probably the most straightforward:
$ g++ -c cpp2c.cpp -o cpp2c.o
$ gcc -c csayhello.c -o csayhello.o
$ gcc cpp2c.o csayhello.o -lstdc++ -o cpp2c
Notice that it is necessary to specify the standard C++ library in the final link because
the gcc command is used to invoke the linker instead of the g++ command. If g++ had
been used, the C++ library would have been implied.
It is most common to have the function declarations in a header file and to have the
entire contents of the header file included as the extern "C" declaration. The syntax
for this is standard C++ and looks like the following:
extern "C" {
int mlimitav(int lowend, int highend);
void updatedesc(char *newdesc);
double getpct(char *name);
};
阅读(290) | 评论(0) | 转发(0) |
0

上一篇:UNIX,Linux与FreeBSD

下一篇: Tcl的历史

给主人留下些什么吧!~~