Compiling and Linking: Simple Example with gcc

The goal of this text is to make a small introduction to the compilation process. We will make a library and then link the application code with the library. It is assumed that the librarian is ar and the compiler is gcc. The aim is to obtain rough understanding what steps will be necessary when we go to real things.

The sample code is in example.tar.gz or you can browse it here.

1) Unpacking the archive

It is assumed that the archive is already in the current directory.

$ tar zxvf example.tar.gz

The command creates directory example/lib with files testlib.cpp and testlib.h and directory example/app with file main.cpp. The goal is first to compile and make the library and then link the application with the library.

2) Making library

$ cd example/lib

$ gcc -c testlib.cpp

$ ar cr libtestlib.a testlib.o

The flag -c forces gcc to compile to the object file without linking. The librarian makes a library from the object files. gcc determines the programming language from the file extension and then calls the required compiler automatically.

3) Compiling application

$ cd ../app

$ gcc -c -I../lib main.cpp

File main.cpp contains a pragma #include that requires gcc to find the header testlib.h. In our case, gcc does not know where the header is and we must use -I to tell it. You can use -v to check what the default directories are used by gcc to look for headers.

4) Linking application with the library

Now we want to convert the object file main.o to the executable. Along this way, it is necessary to link it with the library libtestlib.a. The right command is as follows:

$ g++ -o main main.o -L../lib -ltestlib

The flag -o specifies the name of the binary. By default it is a.out (a.exe in Cygwin). The flag -L tells gcc where to search for the library and the flag -l tells gcc with what a library to link. Note that with -l we specify only the main part of the library name.

gcc uses by default many system libraries as well. You can use -v to see what libraries are used and in what directories gcc is looking for them. The reason to use g++ was that by default it links with stdc++ and gcc does not.

5) Running the binary

$ ./main

or

$ ./main.exe

in Cygwin.

More information

$ man gcc

or

$ info gcc

or go to http://gcc.gnu.org/onlinedocs/

A good idea is also to search in Google for gcc tutorial. There are many of them.

$ man ar

or

$ info ar


Comments are closed.