C调用C++动态库,静态库

来源:互联网 发布:java 命令行执行main 编辑:程序博客网 时间:2024/05/18 03:43

 

C调用C++动态库,静态库
//paullib.cpp
1 #include <iostream>
      2 using namespace std;
      3
      4 class paul
      5 {
      6         int a,b;
      7         public:
      8         int add(int a,int b);
      9 };
     10
     11 int paul::add(int a,int b)
     12 {
     13         int sum;
     14         sum=a+b;
     15         return sum;
     16 }
     17
     18 extern "C"          //如果没有则不行;
     19 {
     20         int callfunc()
     21         {
     22                 paul m;
     23                 cout<<m.add(3,4)<<endl;
24         }
     25 }
//paul.c
1 #include <stdio.h>
      2 extern void callfunc();//要被外部函数调用;
      3 int main()
      4 {
      5
      6         callfunc();
      7         return 0;
      8 }
 
静态库:
# G++ -c paullib.cpp
# ar –cr slib paullib.o
#gcc -o paul paul.c -L. slib -lstdc++  //注意这个程序还是要调用c++的库函数,加上-LSTDC++就可以了
注意:nm slib看一下:
 
动态库:
[root@localhost 08-14]# g++ paullib.cpp -fPIC -shared -o libpaul.so
[root@localhost 08-14]# cp libpaul.so /lib
[root@localhost 08-14]# gcc paul.c -L. -lpaul -o paul
注意:-lpaul不要写错了;
[root@localhost 08-14]# nm libpaul.so
00001cd4 A __bss_start
00000944 T callfunc  //注意CALLFUNC后面没有V,如果没有加EXTERN “C” 则有
00000864 t call_gmon_start
00001cd4 b completed.1
00001c80 d __CTOR_END__
00001c78 d __CTOR_LIST__
         U __cxa_atexit@@GLIBC_2.1.3
         w __cxa_finalize@@GLIBC_2.1.3
 
 
不加extern “c”
00001b9c d p.0
000009ee t __tcf_0
0000099a t _Z41__static_initialization_and_destruction_0ii
00000948 T _Z8callfuncv
00000934 T _ZN4paul3addEii
         U _ZNSolsEi@@GLIBCPP_3.2
         U _ZNSolsEPFRSoS_E@@GLIBCPP_3.2
         U _ZNSt8ios_base4InitC1Ev@@GLIBCPP_3.2
         U _ZNSt8ios_base4InitD1Ev@@GLIBCPP_3.2
         U _ZSt4cout@@GLIBCPP_3.2
原创粉丝点击