Keenan's Blog


Creating Libraries in C

While Trying to make my game engine separate from a given project I delved into the world of libraries in C. The current library I created is a shared library which can only be used on linux I think. So in the future I'm gonna try to make it static, but nonetheless it was a very cool learning experience.

To demonstrate I'll show an example file that could be used as a library which can then be used in other programs.


void print_string(char string)
    printf('%s', string);

You then need to compile the code into an object file using the -c parameter

cc -c test.c

The compiler can be any of your choosing I just happen to be using cc

Now that you have compiled the code there should be a file called test.o which will be used to make the shared library. To make the library you need to run the following command

cc test.o -shared -o

In order to actually get the print_string function from you need to have a header file that contains an extern declaration of the function.

#ifndef _TEST_H_
#define _TEST_H_
extern void print_string(char string);

Now usually there's an environment variable you can set on your machine that will share your path to your library so that the compiler knows where the library is but I wasn't able to get it to work, I don't think I was doing it correctly, so I directly copied the header file to my /usr/include/ and the library to the /usr/lib/. I suppose a symlink could work as well that way you don't have to sudo every time you want to compile the library and copy it over.

Now if you want to work with multiple object files you just need to include all the object files you want when you make the library

cc file1.o  file2.o file3.o -shared -o

Then for the header file you need to only make 1 that includes all the declarations you want shared and call it file.h. Also the -shared parameter can be changed -static if you want to make a static library, which might be preferable since it can port over to different operating systems.

cc file1.o  file2.o file3.o -static -o

when alls said and done you should be able to use the library in other project code.


int main(void)
    print_string('This is a test!');
    return 1;

Then you need to compile the code using the library

cc main.c -ltest -o main

and then running ./main should print into the terminal

$ This is a test!

I don't actually know if this code will actually work, I just threw it together as an example. But it should theoretically work.

Moving forward

Now that I have been able to package my files into a shared library I am hoping to actually make my game engine feel like a game engine. One that can handle projects, scenes, scripts, and assets separately. I would also like to refactor my engine so that it can be packaged into a static library, because I would like to be able to use it on other platforms.