Sunday, April 15, 2012

Compiling and Linking using gcc in Command Line under Linux

Let us suppose that we have a simple program "hello world" program: place in the source file helloWorld.c.

Compiling the source file
gcc -c helloWorld.c
  • gcc - invokes the compiler
  • -c - the compiler flag that specifies that only compilation will be done (no linking)
  • helloWorld.c - the path to the C source file
After running this command you will observe that new file helloWorld.o has appeared. This file is the object file resulted after the compilation. In order to create an executable you will need to call the gcc again to do the linking.

Creating the executable
gcc -o helloWorld helloworld.o
  • gcc - invokes the compiler
  • -o - places the output in a specified file (in our case helloWorld), which will represent the executable
  • helloWorld - the executable who resulted
  • helloworld.o - the path to the object file
Running the executable
./helloWorld

Now, let's say that you have 2 source files, main.c and interface.c and main.c uses some functions defined in interface.c.

First, we will need to compile the source files in order to obtain the object files:
gcc -c main.c
gcc -c interface.c
By invoking the gcc, you will obtain 2 object files: main.o and interface.o.

In order to create the executable, you will need to invoke gcc again, but this time both object files will need to be specified.
gcc -o main main.o interface.

Now you will have in your folder the newly created executable main.

Let's say now that the source file interface.c contains a call to the double sqrt(double number) function from math.h. In order to obtain the executable, you will have to manually link to the m (mathematical) library:
gcc -o main main.o interface.-lm

If your program, would have been linked to a user library who we shall call myLib.a placed in /usr/lib/myLib.a, the gcc invocation would had looked like:
gcc -o main main.o interface.o /usr/lib/myLib.a

If you would need to compile and link multiple files (for a larger project), the method presented above will prove to be cumbersome and time consuming. A better method is the use of a makefile, but this will be discussed in another article.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger