Search code examples
clinkershared-libraries

How do I create a library in C?


I am working on a program that is using libgit2. I had kept the code in a single c file. Say:

somefile.c

I compile and use it. Now I want to separate some of the details related to libgit2 into a separate library inside the project. So I created an h file with the data structures that I need and the definitions of the functions I want to use. So far, nothing fancy: init stuff, pass in the path to the repo and s a treeish... those are const * constant.... then In the library c file I have an implementation of the functions in the .h file.

Currently, the layout is like this:

include/mylib.c
include/mylib.h
somefile.c

In include/mylib.h I have one struct and a couple of functions:

struct blah {} blah_info;

int blah_init(cont char * path, const char * treeish);

int blah_shutdown();

In include/mylib.c I include mylib.h:

#include "mylib.h" # notice that I don't have to use "include" in the path

And then I have definitions for the 2 functions that I put in the .h file.

In somefile.c now I am including the library c file, not the .h file (and no need to include git2.h anymore either as that is done in mylib files now).

#include "include/mylib.c"

And this allows me to compile and run the program, just like it did before I separated it into pieces but I know it's possible to include include/mylib.h from the original .c file. I think it requires to build the library before then going into compiling the final program? What steps are required for that?

Right now I'm compiling by hand in a shell script calling GCC in a single shot... so if I need to run more commands to do so, just let me know so that I add them to the script.


Solution

  • In somefile.c, you need to do this:

    #include "include/mylib.h"
    

    And make sure you define these functions in mylib.c:

    int blah_init(cont char * path, const char * treeish) {
    
    }
    
    int blah_shutdown() {
    
    }
    

    And then declare them in mylib.h:

    struct blah {} blah_info;
    
    int blah_init(cont char * path, const char * treeish);
    
    int blah_shutdown();
    

    And when you compile, include both somefile.c and mylib.c as input files.