Creating a Static Library
tags: assembling, compiling, linking
Creating libraries allows you to place code in a container so that it can be used by other programs. You can create a shared library which is loaded into memory and is available for any running process to use, or you can create a static library which is bundled up within an executable in the same manner as linking in another object file. We'll go over static library creation since welibc isn't ready to be a shared library yet.
Static libraries
Rather than being loaded by the operating system and being made available to any process, a static library is linked in at compile time in a similar fashion to a normal object file. This is the method I'll be using for testing welibc.
We can assemble the following code just as we normally would to create an object file, from _start.s:
.globl _start # Declare global _start symbol
_start:
call main # Call main function
mov %rax, %rbx # Copy return value from main as argument to exit(2)
mov $1, %rax # Set rax to syscall number for exit
int $0x80 # Trigger interrupt to call exit
Assemble:
$ gcc -nostdlib -ffreestanding -c -o _start.o _start.s
Then we create an archive with the ar
program:
$ ar cr libwelibc.a _start.o
Write our test code, main_test.c:
int
main(int argc, char *argv[])
{
int ret = 42;
return ret;
}
And compile:
$ gcc -nostdlib -ffreestanding -c -o main_test.o main_test.c
To link against a static library you specify the library's name without the
prepended "lib" using the -l
flag to gcc, and ensuring to pass the path of the
library with the -L
flag:
$ gcc -L./ -nostdlib -ffreestanding -o test_welibc main_test.o -lwelibc
Now you've linked against a static library and you can run your code:
$ ./test_welibc
$ echo $?
42
As welibc comes along it will be built as a static library and then the test code can link against it like above. This should keep things pretty simple for testing the functionality of the library.
comments powered by Disqus