Search code examples
linuxgccdynamic-linkingmosquittolibmosquitto

Linking mosquitto library to hello.c program on Linux


I am trying to compile the mosquitto library with my custom c program. So WHat I have done is wrote a hello.c file, git cloned the latest mosquitto library from the below repository:

https://github.com/eclipse/mosquitto.git

and compiled it with the make command as below:

make

I had to remove the doc target as it was asking for some dependancy library. I don't have admin rights on this machine, hence don't want to be blocked by any dependancy lib. After the compilation what I have is the below:

src/mosquitto 
./lib/libmosquitto.so.1  

The I copied the libmosquitto.so.1 shared lib into a local folder called ~/hello/:

~/hello$ cp ~/mosquitto/lib/libmosquitto.so.1 .

then wrote a hello.c inside ~/hello/ which is as below:

#include <stdio.h>

int main()
{
    printf("Hello World\n");

    return 0;
}

I can compile the hello.c and run it as below:

gcc -o hello hello.c
./hello
Hello World

But if I try to link the binary with the mosquitto library I get an error like the below:

gcc -o hello hello.c -lmosquitto
/usr/bin/ld: cannot find -lmosquitto
collect2: error: ld returned 1 exit status

The libmosquitto.so.1 lives in the same folder as the hello.c. I don't want to install the mosquitto library, rather would like to keep in a local folder and be able to link it. I have also tried the below with the hope that the -L. would point the linker to the present directory for the shared lib file but still get the same error:

 gcc -o hello hello.c -L. -lmosquitto
/usr/bin/ld: cannot find -lmosquitto
collect2: error: ld returned 1 exit status

My ultimate objective is to cross compile the library for an arm target. So really need to understand how the linking of the shared library is failing so that I can use the same experience while cross compiling and link for the target. At the moment I am doing this on a x86 platform. Can anyone please help?


Solution

  • /usr/bin/ld: cannot find -lmosquitto

    The linker doesn't look for libmosquitto.so.1 -- it only looks for libmosquitto.a or libmosquitto.so.

    Solution: ln -s libmosquitto.so.1 libmosquitto.so

    ./pub: error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory

    The problem here is that the runtime loader doesn't look in the current directory for libmosquitto.so.1 -- it only looks in system-configured directories.

    You could fix this by adding export LD_LIBRARY_PATH=$HOME/mosquitto/lib, but this is suboptimal -- your binary will work or not depending on the environment.

    A better solution is to change your link command like so:

    gcc -o hello hello.c -L. -lmosquitto -Wl,-rpath=$HOME/mosquitto/lib