简体   繁体   中英

How can I create and use my own static library in C?

I want to my make own library and have it use the same syntax as the standard C libraries as in

#include<mylib.h>

So that it looks like #include and some of the libraries that are included with C.

Can I make the library static as opposed to linking so that I can compile it in GCC without additional arguments, as if I were using another library like stdio.h or string.h?

This seems simple enough.

  • Develop the library (create as many source files as you need).

  • Build the source files into a shared library (.so) using a tool like CMAKE (which i strongly recommend).

  • Copy that library to your library path (ie /usr/lib )

  • Later on, all you have to do is import your lib: (i) in the source using #include<mylib.h> ; (ii) when building (also using CMAKE) or using the flag ( -lmylib ) in the GCC compiler: gcc -lmylib myfiles.c -o myoutput.

In addition to #include "mylib.h", you need to add -lmylib command line to the compiler (more specifically linker) when using the library. I assume that the your library archive created through ar command is named as libmylib.a .

Usually, we do not write 'manually' build instructions, but we rely on tool that generates build chains. There are quite a lot of them, the most know are probably autotools and cmake (under Linux).

I would suggest you to have a look to cmake examples and/or documentation to get your code built.

There are quite a lot of differences between static and dynamic libs, and you will also need to package somehow your lib if you really want to use it like 'standard' lib (like libxml2, openssl, etc.)

A lot to say about it, but you should first have a look to 'how to build' your lib, and then see how to make it easy to use, IMHO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM