您的位置:首页 > 编程语言 > C语言/C++

C++调用C函数[待修改]

2010-09-19 17:54 239 查看
//test.cpp 文件
#include <iostream>
#include <cstdio> //对应C中的 stdio.h  [C++中调用C的库函数,有对应C++版本如,cstring]
#include <cstring> //对应C中的 string.h
#include "./cfun_add.h"//调用C写的函数
using namespace std;
int main (void)
{
cout<<"Hello C++"<<endl;
printf ("Hello c function.num=%d/n", 123);
int ret = 0;
char str1[] = "123";
char str2[] = "23";
ret = strcmp (str1, str2);
if (!ret) {
printf ("%s and %s are the same.", str1, str2);
} else {
cout<<"不一样。"<<endl;
}
cout<<"3+4="<<add_c(3, 4)<<endl;//[C++中调用C写的函数]
return 0;
}
//cfun_add.h 文件
int add_c (int a, int b);
// cfun_add.c 文件
#include <string.h>
#include <stdio.h>
int add_c(int a, int b)
{
puts("add_c is called./n");
return a+b;
}
编译:
# g++ -o test cfun_add.c test.cpp
成功生成 test,
# ./test  //执行
使用库方式:
静态库:
# gcc -c cfun_add.c  //生成了 cfun_add.o
# ar -rcs libcfun_add.a cfun_add.o  //使用归档命令生成静态库cfun_add.a
//使用静态库
在 test.cpp中一定要有如内容,
extern "C"{
#include "cfun_add.h"//调用C库中的函数
}
# g++ -o test t.cpp -L. -lcfun_add  //生成test -L.表示库文件libfun_add.a在当前目录中,-lcfun_add
其他:略。											//表示引用静态库文件libfun_add.a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: