Skip to content

Instantly share code, notes, and snippets.

@bismarckjunior
Created November 28, 2017 21:58
Show Gist options
  • Save bismarckjunior/336874e5d9ce11d2b4b1dd7c2ef5ea46 to your computer and use it in GitHub Desktop.
Save bismarckjunior/336874e5d9ce11d2b4b1dd7c2ef5ea46 to your computer and use it in GitHub Desktop.
Shared library

Shared Library (c++)

Bibliotecas são arquivos que guardam o código já compilado. Uma shared library é usada por um executável em tempo real de execução. Por outro lado, uma static library é encapsulada dentro do executável no momento da compilação.

Shared libraries são identificadas pelas extensões: *.so (Linux), *.dll (Windows) e *.dylib (OS X).

1. LINUX (*.so)

Arquivos:

  • function.h
  • function.cpp
  • main.cpp

Criando a Biblioteca

  1. Compilar arquivos *.cpp, gerando os respectivos arquivos *.o.

    $ g++ -c main.cpp function.cpp

  2. Criar a biblioteca "libfunc.so" com os *.o gerados.

    $ g++ -shared -fPIC -o libfunc.so function.o

  3. Criar o executável "runner" utilizando a biblioteca libfunc.so.

    $ g++ main.cpp ./libfun.so -lm -o runner

  4. Rodando executável

    $ ./runner

Exemplo:

// function.h

#ifndef __FUNC__
#define __FUNC__

int func1(int a);

#endif;

// function.cpp

#include "functions.h"

int func1(int a){
	return a+50;
}

// main.cpp

#include <iostream>
#include "functions.h"

using namespace std;

int main()
{
	cout<< func1(6)<<endl;	
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment