5

Suppose I have some code written in C with some data structures defined and some functions to work with those structures and all that is in a directory called src1. Suppose now I want to distribute this code.

If I want to use the external code in src1 in a project what should I do? Should I compile the code in src1 to an .a archive and then include that archive in the other projects I want to use?

Basically what I need to know is the correct conventions to use external code in a project.

Thanks in advance.

petermlm
  • 930
  • 4
  • 12
  • 27

3 Answers3

7

To distribute the code in the form of libraries you need follow the below steps:

  1. List down the set of structure, functions, macros etc which you want to expose to other projects.
  2. Group the set of data listed in Point-1 into a set of header files. Rest of your internal stuff can be in other header files.
  3. Compile your code into a static(It will .a for linux based systems or .lib for windows) or dynamic library (It will be a .so/.sl for linux based systems or .dll for windows)
  4. Provide your library and the set of exposed header files (as decided in point-2 above) to the other projects.

Link for creating static or shared libraries using gcc is here

Link for creating static or dynamic libraries in Windows using MSVC is here

Jay
  • 24,173
  • 25
  • 93
  • 141
1

Yes, you can use a static library, which is an .a file in Linux, and typically a .lib in Windows. This also requires that you share the header of course, so the code that uses the library can have the proper data structure definitions.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

You can use any format (.a or .so) to distribute your library. The first one is static ally Inked and the second one is dynamically linked. To know more see this answer Difference between static and shared libraries?

Which ever you use you always link it in the same way.

gcc -L/path/to/lib -lsrc1 source.c -o source.o

Here, /path/to/lib can contain any of your previously compiled libsrc1.so or libsrc1.a

Community
  • 1
  • 1
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187