zoukankan      html  css  js  c++  java
  • linux下创建和使用自己的动态链接库

    linux下面的.so文件一般是指动态链接库文件,通过动态链接可以节省资源使得程序自身体积更小

    如果多个程序使用到了相同的模块,可以更加充分的利用程序段,差别是动态库第一次加载的时候

    程序肯恩会启动的慢点

    下面介绍如何用G++生成和使用自己的动态链接库文件

    实例:现在有文件replace.h 和replace.cpp通过G++将其编译成.so文件,然后在main.cpp文件中调用

    replace.h文件中定义的函数

    程序清单:

    replace.h文件内容:

    1 #include <stdio.h>
    2 int length(const char* string);
    3 char* replace(const char* string);

    replace.cpp内容:

    #include <stdio.h>
    2 #include "replace.h"
    3 int length(const char* string)
    4 {
    5 if (string == NULL) return 0;
    6 int length = 0;
    7 for (int i = 0; *(string + i) != ''; ++i) {
    8 if (*(string + i) == ' ') {
    9 length += 3;
    10 } else
    11 ++length;
    12 }
    13 return length;
    14 }
    15
    16 char* replace(const char* string)
    17 {
    18 int len = length(string);
    19 if (len == 0) return NULL;
    20 char* result = new char[len + 1];
    21 int j = 0;
    22 for (int i = 0; i < len; ++i, ++j) {
    23 if (string[i] == ' ') {
    24 result[j] = '%';
    25 ++j;
    26 result[j] = '2';

    27 ++j;
    28 result[j] = '0';
    29 } else {
    30 result[j] = string[i];
    31 }
    32 }
    33 result[len] = '';
    34 return result;
    35 }
    36

    main.cpp内容:

    1 #include <stdio.h>
    2 #include "replace.h"
    3 int main()
    4 {
    5 const char* p = "hjash sdfds fdsfds fds f dsf ds f s";
    6 printf("%s ", p);
    7 printf("%s ", replace(p));
    8 return 0;
    9 }
    10

    第一步:生成.so文件

    g++ replace.cpp -fPIC -shared -o libreplace.so

    这个时候ls查看当前目录可以发现已经多了一个 libreplace.so

    第二步:编译连接动态库

    g++ main.cpp -L -lreplace -o test

    这个时候发现当前目录下面又多了一个test可执行文件

    ./test

    结果:

    ./test: error while loading shared libraries: libreplace.so: cannot open shared object file: No such file or directory

    原因是 libreplace.so文件并没有加入系统链接库路径

    执行export LD_LIBRARY_PATH=当前路径

    现在运行程序就可以得到正确的结果了

  • 相关阅读:
    vue导航守卫和axios拦截器的区别
    js中的深拷贝与浅拷贝
    Storyboard中拖拽控件不能运行的问题(在运行的时候,相应的控件代码没有被执行)
    关于stringWithFormat:
    两层嵌套的JSON包的解法
    button的action属性如果有参数,必须加“:”
    iOS 协同开发出fatal error: file 'XX-Prefix.pch' has been modified since the precompiled header was built
    [转] Objective-C语法快速参考
    iOS应用程序内存查看工具
    XCode快捷键大全
  • 原文地址:https://www.cnblogs.com/candycloud/p/3847456.html
Copyright © 2011-2022 走看看