Thursday, November 4, 2010

A C program in Ubuntu

The GNU C compiler(gcc).
This is the GNU C compiler, a fairly portable optimizing compiler for C.
This is a dependency package providing the default GNU C compiler.
—————————————————————————————————
The first thing to do is to check if gcc is installed in your system.
This can be done by opening a terminal
and typing:
which gcc
This gives the location where it is installed.
Usually, the output is :
/usr/bin/gcc
If gcc is not installed type :
sudo apt-get install build-essential
To check the version type
gcc -v
The output is :
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.
Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --
libexecdir=/usr/lib --without-included-gettext
--enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib
--enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug
--enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686
--with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu
--target=i686-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)
The next part is to compile and run a C program.
Type the program in any editor
and save it as hello.c
Sample code is given below:
#include "stdio.h"
int main()
{
printf("Hello World\n");
printf("C in Linux\n");
return 0;
}
In your terminal, go to the location where you have saved your program.
cd Desktop, if it has been saved in the desktop.
Then type
gcc hello.c -o hello
followed by
./hello
You should get the output on your screen.
If u get any permission error then,
chmod +x hello.c
Digging a little deeper
I wrote a code and saved it as test.c
#include "stdio.h"
void main()
{
for (int i=0;i<10 ;i++)
printf("%d",i);
}
When I tried to compile using
gcc test.c -o test
it gave an error:
test.c: In function ‘main’:
test.c:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
test.c:5: note: use option -std=c99 or -std=gnu99 to compile your code
It turns out that declaring 'i' inside the for loop is illegal in C90 mode, which
is the default mode. To compile it you either need to declare 'i' outside the for loop
i.e
int i
for(i=0...)
this works fine.
Or to use the c99 mode, where it is legal to declare variables inside the for loop.
Thus,
gcc test.c -std=gnu99 -o test
or
gcc test.c -std=c99 -o test

http://oddabout.com/?p=69

No comments:

Post a Comment