How can I solve the problem with linking .so library to c code?


I am having problem linking .so file to my main1.c

At first, I used the command below to create .so file from multiple c source and header files.

arm-linux-gnueabi-gcc -shared -o ~/Docs/examples/ -fPIC *.c -lpthread -ldl -lm

Then I created main1.c file in the same folder (~/Docs/examples) and used the following command to generate another .so file for main1.c that uses

arm-linux-gnueabi-gcc -shared -o main1.c -L ~/Docs/examples -lmylib1 -lpthread -ldl -lm

When I copy the file to another folder and try to use it with another code.c file it isn’t working. The new folder contains only and code.c. Here is the command that I used.

arm-linux-gnueabi-gcc -shared -o code.c -L ~/Docs/newlocation -lmylib1 -lpthread -ldl -lm

But when I add {-idirafter ~/Docs/examples} and included the original location of it seems to work.

Here are some of my attempts:

**[email protected]:~/Docs/newlocation$** ls


**[email protected]:~/Docs/newlocation$** arm-linux-gnueabi-gcc -shared -o code.c -L ~/Docs/newlocation -lmylib1 -lpthread -ldl -lm

code.c:1:10: fatal error: comm_genlib.h: No such file or directory

1 | #include "comm_genlib.h"

| ^~~~~~~~~~~~~~~

compilation terminated.

**[email protected]:~/Docs/newlocation$** arm-linux-gnueabi-gcc -shared -o code.c -L ~/Docs/newlocation -idirafter ~/Docs/examples -lmylib1 -lpthread -ldl -lm

**[email protected]:~/Docs/newlocation$** ls


I don’t know why it works when I added -idirafter ~/Docs/examples

How to fix this?


There are two important phases during compilation: the transformation of the source code into raw binary and the packaging of all the raw binaries necessary to form an executable, or a shared library.

For the first phase, the compiler must have access to all the source files: the ‘.c’ referenced on the command line as well as all the other source files referenced in these ‘.c’ by #include instructions.

To find these sources, the compiler looks in some compiler-specific directories, like /usr/include; it also searches the current directory.

But the ~Docs/examples directory is not part of the default search directories. So the reference to comm_genlib.h cannot be resolved and the compilation crashes.

The -idirafter option adds this directory to the search paths. This is why compilation works when added.

During this first phase, binaries, like .so files, are not used. They will be in the second phase of the compilation. Anyway, .h files are not included in binaries ; there are only used as pure text files during first phase.

There’s no particular solution to the problem you’re having, because in the end it’s not a problem, it’s the way the ‘C’ compiler works.

Answered By – Joël Hecht

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published