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.

2

1 Answer 1

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.

6
  • 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, 2013 at 13:16
  • @rubenvb It does work on windows. You need to install cygwin. Aug 20, 2013 at 13:30
  • Instead of LD_LIBRARY_PATH use g++ -Wl,-rpath,\$ORIGIN r.cc t.so. Aug 20, 2013 at 13:31
  • @Maxim Cygwin != Windows. And Cygwin needs dllexport nonetheless.
    – rubenvb
    Aug 20, 2013 at 13: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, 2015 at 19:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.