4

I am using Ubuntu Linux I have made a custom static library Mylib.a, I can include it to only those c files which are in the same directory as the static library.

I want to make it a general library so that I can include the library file to any c file I want irrespective of its location

2
  • gcc will search in specific folders, see documentation for more details (you may start with LIBRARY_PATH environment variable and also compile with -v to see where it search). Alternatively you may give full path (anywhere it is) on gcc command line. Commented Nov 24, 2015 at 11:15
  • How do you include this library? You have to include the header and link the library. Commented Nov 24, 2015 at 11:33

3 Answers 3

4

To use a static library you have to include the header in the .c files that use the library and then link the library. If the name of the library is libstatic.a then:

gcc -o yourprog yourprog.c -lstatic

If the library is not in the same directory use the -L option to specify the path:

gcc -o yourprog yourprog.c -L/path-to-lib -lstatic

(see also this post: How to link to a static library in C?)

Sign up to request clarification or add additional context in comments.

Comments

3

You can copy that .a file (or better .so file) to a standard location such as /usr/lib.

If you compile from the command line, you also need to specify the library name (even if it's already in /usr/lib), the same way when you specify standard library like -lpthread.

You can also specify the library path and library name in makefile

6 Comments

I did copy it to /usr/lib but it still gives me compilation error
Is it link error or compilation error? Did you remember to copy the .h file to /usr/include as well?
I did not copy the .h file
It works! I still have to mention the library name when I run the object file gcc -o ex ex.o -l_mylib Is there a way to add this library permanently to a MakeFile
Is there a way to create a custom lib that can be called without the -l<namelib> ? (like -lpthread)
|
1

As Adriano wrote, you can include a library even if it is not in the same directory as your c file. However, you have to specify where to look for for the libraries you use.

see here: https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html

Hope I helped,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.