gcclinkershared-librariesstatic-libraries

Using my own static/dynamic library: HOW TO compile and link against (the right way to do the things properly)


Context:

I have just created my own library (using CMake):

libmyownsomething.a <--- static version of the compiled library
libmyownsomething.so <--- dynamic version of the same library
libmyownsomething.h <--- the header file to be included in other project

Questions:


Solution

  • To be able to link agains your library with just -lmyownsomething, you need to have libmyownsomething.so (or .a, for static linking) in one of the directories you linker searches by default.

    I found this in texinfo documentation for GNU ld (library search path in linker script):

    'SEARCH_DIR(PATH)'

     The 'SEARCH_DIR' command adds PATH to the list of paths where 'ld'
     looks for archive libraries.  Using 'SEARCH_DIR(PATH)' is exactly 
     like using '-L PATH' on the command line
    

    Now, GNU ld (ld.bfd to be precise) uses a default linker script, which can be obtained with --verbose. Let's see what search dirs there are by default (on my system, anyways -- that might well depend on configuration; if you are going to distribute your library, you probably want to make the most portable choice):

    $ ld --verbose |& grep SEARCH_DIR 
    SEARCH_DIR("/usr/x86_64-pc-linux-gnu/lib64"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/local/lib"); SEARCH_DIR("/usr/x86_64-pc-linux-gnu/lib");
    

    To answer the question about #includeing files, you need to consult the compiler documentation, or perhaps the POSIX standard. (However, I'd recommend either going with the simplest choices -- see below -- or providing a configurable way to install your files e.g. with --prefix build time option. Then the user/packager can decide the best place to put them for themselves. But nothing keeps you from providing sane defaults. Same goes for libraries, but I tried to address that part of the question exactly how it was asked.)

    Generally, this stuff varies from system to system, but they usually follow the Filesystem Hierarchy Standard. I think, /usr/include and /usr/lib is the safest choice. Another good practice is using e.g. pkgconf mechanism.

    Hope this helps. I really should have asked about your use-case first: who are you going to distribute your software to, and how? Anyway, be sure to post comments. Also, I wonder if this is Stackoverflow material; perhaps it needs moving some place else.