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).
- function.h
- function.cpp
- main.cpp
-
Compilar arquivos *.cpp, gerando os respectivos arquivos *.o.
$ g++ -c main.cpp function.cpp
-
Criar a biblioteca "libfunc.so" com os *.o gerados.
$ g++ -shared -fPIC -o libfunc.so function.o
-
Criar o executável "runner" utilizando a biblioteca libfunc.so.
$ g++ main.cpp ./libfun.so -lm -o runner
-
Rodando executável
$ ./runner
// 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;
}