Sunday, October 4, 2009

C and C++ Compiling in Linux - Get It Ready

Not all Linux distributions are ready for C and C++ compilation right after installation. Some of them are missing compilers, others - some basic libraries. I decided to write the note how to make it working.

Create a new directory for the tests and save a file HelloWorld.c in it. The file has the following content:

#include <stdio.h>

main ()
{
printf ( "Hello World!\n");
}

On Mepis 7.0 machine cc and gcc C compilers were installed:

$ whereis cc gcc
cc: /usr/bin/cc
gcc: /usr/bin/gcc /usr/lib/gcc

but attempt to compile the C code ended up with an error :

$ cc HelloWorld.c -o HelloWorld_cc
HelloWorld.c:1:19: error: stdio.h: No such file or directory
HelloWorld.c: In function 'main':
HelloWorld.c:5: warning: incompatible implicit declaration
of built-in function 'printf'

The missing "stdio.h" library comes with the "build-essential" package. Mepis has Synaptic package manager - start it and install the package. After that compilation passes through without an error:

$ cc HelloWorld.c -o HelloWorld_cc
$ ./HelloWorld_cc
Hello World!

$ gcc HelloWorld.c -o HelloWorld_gcc
$ ./HelloWorld_gcc
Hello World!

Mepis 8.0 did not have a problem with C program, but neither c++ nor g++ compiler was installed:

$ whereis c++ g++

gave out nothing. With a package manager (again Synaptic in my case) install the compiler(s). After that "whereis" can find them:

$ whereis c++ g++
c++: /usr/bin/c++ /usr/include/c++
g++: /usr/bin/g++

Create HelloWorld.cpp C++ file:

#include <iostream>
using namespace std;

int main ()
{
cout << "Hello World!\n";
return 0;
}

Compilation is successful with the both compilers:

$ g++ HelloWorld.cpp -o HelloWorld_g++
$ ./HelloWorld_g++
Hello World!

$ c++ HelloWorld.cpp -o HelloWorld_c++
$ ./HelloWorld_c++
Hello World!

0 comments:

Post a Comment