c++linkerlibraries

How can I learn to include and link to libraries?


I'm trying to teach myself C++ programming. The C++ is the easy part. Some patience and good reference material goes a long way. Including and linking against libraries is the hard part. The instructions provided usually assume some knowledge which I don't have and don't know how to aquire without painfully slow trial and error.

The latest concrete example is http://cpp-netlib.org/

I've spent the whole afternoon trying to get it to work and I still don't even an idea why it's not working.

How can I learn this skill from the ground up?

Is it it normal to have such enormous difficulties learning how to do this?


Solution

  • Well, the principle is pretty much always the same for any C++ compiler (the option flags mentioned are quite standard but might differ for particular compilers):

    1. Install a library you want to use in your system (this may include a step to compile this library with your particular compiler toolchain).
    2. Setup the include paths to be used for this library using the -I option
    3. Use the headers of the library API in your code (#include <libheader.h>)
    4. Setup the library paths to be used for this library using the -L option, tell the linker which libraries to link using -l<extra>, where extra should refer to some file named lib<extra>.a or lib<extra>.lib

    Things to note:

    1. Third party libraries might depend on further libraries you'd also need to install (compile with the same toolchain as your target uses)
    2. On Windows using the MS Visual Studio (Express) toolchain you'll need to take care choosing the right library versions that are compliant with the 'threading model' and in general 'debug' / 'non-debug' library versions.

    An (appropriate and useful) IDE will usually let you choose the toolchain (MinGW GCC, MS VS compiler, LLVM, etc.) on project setup, and offer some properties dialog to set these options.
    What's necessary to setup for the toolchain, 3rd party libraries, IDE and OS you're using is a bit different learning curve and depends on what you want to use in particular.