I would like to know how to create a new library in C++
. if anyone can give an example, it can be a generalized example.
I would like to know how to create a new library in C++
. if anyone can give an example, it can be a generalized example.
Two types of libraries will be explained: static and shared. Below is an example of creating both command-line in Linux .
Static library: Used in compilation
main.cpp
#include "libprint.h"
int main(){
//Função guardada numa biblioteca estática
print_ola("Rafael");
}
libprint.h (Static Library Header) - it's good to create a header file for your library.
#ifndef LIBPRINT_H
#define LIBPRINT_H
void print_ola(const char *);
#endif
printola.cpp (Code of your static library)
#include "libprint.h"
#include <iostream>
void print_ola(const char *nome){
std::cout << "Olá, " << nome << "!" << std::endl;
}
Steps to create the static library:
Generate the object code of printola.cpp: g++ -c printola.cpp
. Now package the object code in the form of a library:
ar crv libprintola.a printola.o
ar crv libprintola.a printola.o printalgo.o etc
).
Compilation and execution:
g++ main.cpp -o programa libprintola.a
./programa
Exit: Hello, Rafael!
Shared Libraries: - (with the same old files!)
g++ -c -fpic printola.cpp
creates the object object code that can be used as shared.
g++ -shared -o libprintola.so printola.o
creates your shared library named libprintola.so !
Testing: g++ -L. -Wl,-rpath=. -Wall -o programa main.cpp -lprintola
That should display the same result. (but beware! each works differently!)