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.

Sign up to request clarification or add additional context in comments.

6 Comments

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 It does work on windows. You need to install cygwin.
Instead of LD_LIBRARY_PATH use g++ -Wl,-rpath,\$ORIGIN r.cc t.so.
@Maxim Cygwin != Windows. And Cygwin needs dllexport nonetheless.
@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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.