views:

488

answers:

6

I am looking for basic examples/tutorials on:

  1. How to write/compile libraries in C++ (.so files for Linux, .dll files for Windows) and...
  2. How to import and use those libraries in other code.

Many thanks in advance!

+6  A: 

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.

wilhelmtell
+2  A: 

Two samples I got off Google:

A Windows DLL

A Shared Library

Vulcan Eager
A: 

@mutable

I am able to compile your examples but when I attempt to run the executable I get:

$ ./a.out 
./a.out: error while loading shared libraries: t.so: cannot open shared object file: No such file or directory

I'm sure I am missing something simple but I cannot find it.

brian newman
+2  A: 

@bcnewman

I am able to compile your examples but when I attempt to run the executable I get [an error loading shared libraries]

Did you install the newly created library somewhere along your LD_LIBRARY_PATH or equivalent? Did you update any dynamic loader cache (see man ldconfig on linux)?

dmckee
A: 

@mutable & @dmckee

Got it working ... Thank both of you!

brian newman
+1  A: 

@bcnewman

When having trouble with libraries not being found i find ldd very useful

$ ldd </path/to/elf/file>

@mutable

You can skip out on LD_LIBRARY_PATH when you're not installing you library by adding

-Wl,-rpath,<path>

to the compilation of your executable in pre-install mode. You can set to the current directory in this case

Flame