Generation and call the static and dynamic library under Linux

Static library dynamic library

1. Generate dynamic libraries and invoke

Create a file for generating .so

// add.h
#include<iostream>
int add(int a,int b);

//add.cpp
#include "add.h"
int add(int a, int b)
{
    return a+b;
}

// hello.h
#include<iostream>

using namespace std;

void hello();
// hello.cpp
#include"hello.h"

using namespace std;

void hello()
{

    cout << "Hello World!!"<<endl;
}

So generated using g ++

Implementation of g ++ add.cpp hello.cpp -fPIC -shared -o libtest.so two .cpp files generated test.so file

 

 Creating main.cpp call .so file

#include"add.h"
#include"hello.h"

using namespace std;

int main(int argc,char *argv[])
{
    int a = 20;
    int b = 30;
    cout << "a + b = " << add(a,b)<< endl;
    hello();
    return 0;
}

g++ main.cpp -L. -ltest -o main 

-L parameters: the path specified in the library so you want to link (such as -L represents the current path, -L ../ so indicate so subfolder to the parent directory of the current path of the folder)

-l parameters: specify the name of the library to be connected, such as -ltest pledged to link libtest.so library

 

直接运行会报错 因为没有链接到.so文件,需要在./mian之前告诉so文件的位置 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:./libtest

Guess you like

Origin www.cnblogs.com/wangxiaobei2019/p/12018534.html