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/libmylib1.so -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 libmylib1.so
arm-linux-gnueabi-gcc -shared -o libmain2.so main1.c -L ~/Docs/examples -lmylib1 -lpthread -ldl -lm
When I copy the libmylib1.so file to another folder and try to use it with another code.c file it isn't working. The new folder contains only libmylib1.so and code.c. Here is the command that I used.
arm-linux-gnueabi-gcc -shared -o libcode1.so code.c -L ~/Docs/newlocation -lmylib1 -lpthread -ldl -lm
But when I add {-idirafter ~/Docs/examples} and included the original location of libmylib1.so it seems to work.
Here are some of my attempts:
**abc@abc-TULPAR-T5-V21-4:~/Docs/newlocation$** ls
code.c libmylib1.so
**abc@abc-TULPAR-T5-V21-4:~/Docs/newlocation$** arm-linux-gnueabi-gcc -shared -o libcode1.so 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.
**abc@abc-TULPAR-T5-V21-4:~/Docs/newlocation$** arm-linux-gnueabi-gcc -shared -o libcode1.so code.c -L ~/Docs/newlocation -idirafter ~/Docs/examples -lmylib1 -lpthread -ldl -lm
**abc@abc-TULPAR-T5-V21-4:~/Docs/newlocation$** ls
code.c libcode1.so libmylib1.so
I don't know why it works when I added -idirafter ~/Docs/examples
How to fix this?
CodePudding user response:
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.