10

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.

brian newman
  • 3,964
  • 5
  • 25
  • 24
  • 1
    worth a look - also covers static vs dynamic libraries : http://www.learncpp.com/cpp-tutorial/a1-static-and-dynamic-libraries/ – Graham Griffiths Aug 20 '13 at 13:14
  • also this for code to dynamically load a shared library (with dlopen) : http://stackoverflow.com/questions/496664/c-dynamic-shared-library-on-linux – Graham Griffiths Aug 20 '13 at 13:17

1 Answers1

18

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
  • 57,473
  • 20
  • 96
  • 131
  • 1
    This is a terrible explanation. It doesn' work on Windows, doesn't even touch what Windows adds to this, and throws away everything that was in `LD_LIBRARY_PATH`... – rubenvb Aug 20 '13 at 13:16
  • @rubenvb It does work on windows. You need to install cygwin. – Maxim Egorushkin Aug 20 '13 at 13:30
  • Instead of `LD_LIBRARY_PATH` use `g++ -Wl,-rpath,\$ORIGIN r.cc t.so`. – Maxim Egorushkin Aug 20 '13 at 13:31
  • @Maxim Cygwin != Windows. And Cygwin needs `dllexport` nonetheless. – rubenvb Aug 20 '13 at 13:38
  • @rubenvb Let's not play with words. You said _It doesn' work on Windows_ but it does if you install cygwin. Second, you don't need to declare functions and variables as exported with cygwin because it automatically exports all symbols with external linkage (like Linux/UNIX linkers do), see http://sourceware.org/binutils/docs/ld/WIN32.html – Maxim Egorushkin Aug 20 '13 at 14:38
  • 1
    @rubenvb your point about LD_LIBRARY_PATH should be cleared up a bit. This doesn't overwrite it permanently, because all of these changes would be local to that particular shell. Assuming this would be in a makefile for a realistic problem it would only make changes in the subshell spawned by make. This is still not the best way to do it, but for those who may get confused this wont ruin your compiler forever. – Ajay Aug 11 '15 at 19:15