Linux C调用C++库

来源:互联网 发布:电视棒软件安卓版 编辑:程序博客网 时间:2024/04/30 21:47

头文件

//cppmodule.h#ifndef _CPPMODULE_H_#define _CPPMODULE_H_#ifdef __cplusplus#define EXTERN extern "C" #else#define EXTERN extern#endifEXTERN int add(int x, int y);EXTERN const char *stringtest(int argc, char *argv[]);#endif

C++实现

/* * ===================================================================================== * *       Filename:  cppmodule.cpp * *    Description:  test c and cpp * *        Version:  1.0 *        Created:  2012年09月25日 11时16分33秒 *       Revision:  none *       Compiler:  gcc * *         Author:  (http://blog.csdn.net/njzhiyuan) *   Organization:   * * ===================================================================================== */#include <iostream>#include <string>#include "cppmodule.h"using namespace std;using std::string;int add(int x, int y) {int sum;sum = x + y;cout << x << " + " << y << " = " << sum << endl ;return sum;}const char *stringtest(int argc, char *argv[]) {string s = "The comand line is :\n";for (int i = 0; i < argc; ++i) {s.insert(s.end(), ' ');s.append(argv[i]);}return s.c_str();}


C调用


/* * ===================================================================================== * *       Filename:  test.c * *    Description:  test * *        Version:  1.0 *        Created:  2012年09月25日 11时28分13秒 *       Revision:  none *       Compiler:  gcc * *         Author:   (http://blog.csdn.net/njzhiyuan) *   Organization:   * * ===================================================================================== */#include <stdio.h>#include "cppmodule.h"int main(int argc, char *argv[]) {add(2, 3);printf("%s\n", stringtest(argc, argv));return 0;}

执行命令:

$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright © 2011 Free Software Foundation, Inc.
本程序是自由软件;请参看源代码的版权声明。本软件没有任何担保;
包括没有适销性和某一专用目的下的适用性担保。

$ g++ -fPIC --shared -o libcppmodule.so cppmodule.cpp

编译C文件为可执行文件:

方式一:

$ gcc -o test test.c -L. -lcppmodule


执行:
$ LD_LIBRARY_PATH="$LD_LIBRARY_PATH:." ./test -a -b --dd
2 + 3 = 5
The comand line is :
 ./test -a -b --dd

方式二:

$ gcc -o test test.c -L. -lcppmodule  -Wl,-rpath,.

(注意最后的点号,代表当前路径,当然也可以根据libcppmodule.so的位置,指定为其他路径)


执行:

$./test -a -b --dd
2 + 3 = 5
The comand line is :
 ./test -a -b --dd



原创粉丝点击