Saturday 26 October 2013

Compilation Process in C



Compiling a C Program:

gcc <options> program_name.c

Options:
-----------
-Wall: Shows all warnings
-o output_file_name: By default a.out executable file is created when we compile our program with gcc. Instead, we can specify the output file name using "-o" option.
-g: Include debugging information in the binary.


Linking Multiple files to make executable file:

If we have two programs say prog1.c and prog2.c for one single task then we can make single executable file using following instructions

First, compile these two files with option "-c"
gcc -c prog1.c
gcc -c prog2.c

-c: Tells gcc to compile and assemble the code, but not link.

We get two files as output, prog1.o and prog2.o
Now, we can link these object files into single executable file using below instruction.

gcc -o prog prog1.o prog2.o

Now, the output is prog executable file.
We can run our program using
./prog


Linking with other libraries:

Normally, compiler will read/link libraries from /usr/lib directory to our program during compilation process.
But, there are some case where we need to link our programs with libraries like pthreads and realtime libraries (rt library).
Use below instruction for this purpose

gcc <options> program_name.c -lpthread -lrt

-lpthread: Link with pthread library
-lrt: Link with rt library
Option here is "-l<library>"

Another option "-L <dir>" used to tell gcc compiler search for libraries in given <dir> directory.

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...