Search code examples
c++clinuxgccbuild-process

.o files vs .a files


What is the difference between these two file types. I see that my C++ app links against both types during the construction of the executable.

How to build .a files? links, references, and especially examples, are highly appreciated.


Solution

  • .o files are objects. They are the output of the compiler and input to the linker/librarian.

    .a files are archives. They are groups of objects or static libraries and are also input into the linker.

    Additional Content

    I didn't notice the "examples" part of your question. Generally you will be using a makefile to generate static libraries.

    AR = ar 
    CC = gcc
    
    objects := hello.o world.o
    
    libby.a: $(objects)
        $(AR) rcu $@ $(objects)
    
    %.o: %.c
        $(CC) $(CFLAGS) -c $< -o $@
    

    This will compile hello.c and world.c into objects and then archive them into library. Depending on the platform, you may also need to run a utility called ranlib to generate the table of contents on the archive.

    An interesting side note: .a files are technically archive files and not libraries. They are analogous to zip files without compression though they use a much older file format. The table of contents generated by utilities like ranlib is what makes an archive a library. Java archive files (.jar) are similar in that they are zip files that have some special directory structures created by the Java archiver.