Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing/Using C++ Libraries

Tags:

c++

I am looking for basic examples/tutorials on:

  1. How to write/compile libraries in C++ (.so files for Linux, .dll files for Windows).

  2. How to import and use those libraries in other code.

like image 433
brian newman Avatar asked Sep 03 '08 22:09

brian newman


People also ask

How is C standard library written?

The standard libraries are typically written in C and C++, using a bare minimum of assembly code in order to interact with the functionality provided by the operating system, and most operating systems are written in C as well as a mix of assembly for a handful of things that cannot be done directly in C.

What are the reasons for using libraries in C?

C libraries store files in object code; during the linking phase of the compilation process ( Compilation Process) files in object code are accessed and used. It is faster to link a function from a C library than to link object files from a separate memory sticks or discs.


1 Answers

The code

r.cc :

#include "t.h"

int main()
{
    f();
    return 0;
}

t.h :

void f();

t.cc :

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

void f()
{
    std::cout << "OH HAI.  I'M F." << std::endl;
}

But how, how, how?!

~$ g++ -fpic -c t.cc          # get t.o
~$ g++ -shared -o t.so t.o    # get t.so
~$ export LD_LIBRARY_PATH="." # make sure t.so is found when dynamically linked
~$ g++ r.cc t.so              # get an executable

The export step is not needed if you install the shared library somewhere along the global library path.

like image 125
wilhelmtell Avatar answered Sep 19 '22 08:09

wilhelmtell