Pages

C Program Compilation using GCC


To use GCC  in Windows command prompt, you must make a path in environment variables to directory where gcc.exe is located. In this case, I use gcc.exe from Dev-Cpp. The gcc.exe file is located in Dev-Cpp\bin. There are many gcc.exe that you can use, for example from codeblocks, MinGW, and many other compilers.
The steps to make a path:
Control Panel -> System -> Advanced System Setting -> Environment Variables -> double click Path -> Fill the location. In this case, I use gcc from E:\Dev-Cpp\bin

 Contents of bin directory in Dev-Cpp:

Now, How to Compile a Program.
1.        You should make a source code using text editor. You can use this sample code, code.c.
#define START_VAL 0
int accum = STRAT_VAL;
int sum(int x, int y)
{
         int t = x+y;
         accum += t;
         return t;
}

Save code.c in a directory.
2.       Open command prompt.exe.
3.       In Comand Prompt, move to the directory where code.c is located.
4.       There are a few products that you can create from a compilation process.
-          Preprocess, it doesn’t create any files, it just show you a preprocess in command prompt.
$ gcc –E code.c

-          Compile for assembly file, it creates only code.s
$ gcc –S code.c
Note: -O2 is a optimization type, it is just an option

-          Compile for object file, it creates code.o
$ gcc –c code.c
Note: Object file is a binary file (not a text file) so you can’t see the code in text editor. Object file is a set of instruction of a program that have no link to library so computer still can’t to execute this program.

5.       To make executable file
-          Compile program for object file, like the last step before this.
-          Make a source code, for example main.c, and save it in the same directory where code.c is located. To make executable file the program should has main function.
int main()
{
         return 0;
}
-          Compile all code, for example to create prog.exe as executable file:
$ gcc –o prog code.c main.c

6.       If you want to make a program that use main.c as a main program and the program can use accum variable and sum() function from code.c, You must make some additional file and instruction.
-          Make code.h file :
#ifndef CODE_H
#define CODE_H

int accum;
int sum(int x, int y);

#endif

-          Include code.h in code.c :
#include code.h
#define START_VAL 0
int accum = STRAT_VAL;
int sum(int x, int y)
{
            int t = x+y;
            accum += t;
            return t;
}

-          For example, you make a simple program to show result of sum(4,5). The main.c program is:
#include "code.h"
#include <stdio.h>
int main()
{
printf("%d",sum (4,5));
return 0;
}
Compile all file to prog2.exe using: $ gcc –o prog2 code.c main.c 
after you run prog2 it results 9.
Ok, that's about C compilation steps, instructions, and results.

http://electricalgaze.com

No comments:

Post a Comment