c++调用c函数

下面是从《GCC:the Complete Reference》中摘出来的。
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 <iostream>
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 <stdio.h>
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);
};
对于库函数,应该是直接调用。

对于自定义函数,可能需要改一下头文件。
在所有宏定义和函数说明之加入:
#ifdef __cplusplus
extern "C" {
#endif

在所有宏定义和函数说明之加入:
#ifdef __cplusplus
}
#endif


例如:以下是我自己写得一个头文件
typedef struct{
    int year;
    int month;
    int day;
}date;

int GetWeekNo(date);

修改后就变成
#ifdef __cplusplus
extern "C" {
#endif

typedef struct{
    int year;
    int month;
    int day;
}date;

int GetWeekNo(date);
#ifdef __cplusplus
}
#endif


注意大小写,以及cplusplus前面是两条下划线。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值