Write Your Next Program on Linux

Because it's fun to code on GNU/Linux

Quite a few colleges and schools still teach C/C++/Java programming on Windows — and even worse, on DOS (using Turbo C/C++)! GNU/Linux provides a first class operating system, replete with support for dozens of different programming languages, besides outstanding support for C, C++ and Java. And not only is it free of cost, but it comes with the freedom to modify, share, and extend the IDEs and toolchains! So why on earth do people continue to use outdated and painfully inefficient operating systems or developer tools? This article dispels the myth that Linux is “difficult”, and shows how simple it is to get started with programming on Linux!

Through this article, I want to ask people to start programming on the GNU/Linux operating system (from here on, referred to as just ‘Linux’). Students who are just getting started in programming; educators who teach or have a role in teaching programming to new students; hobbyists who program on Windows — I’m asking all of you to please read on and give Linux a real good try for at least a week. If you agree that programming on Linux is indeed a better experience than your previous platform, then stay with it, and enjoy the freedom that the rest of us do!

Just to clear any misunderstandings, I am not aiming to get you to write code for the Linux kernel itself (though that could well follow as your comfort and programming proficiency grow). Instead, I’m talking about writing user-space programs — including the exercises, homework, and project work that most computer-science study courses include. Before we start, here’s a disclaimer: this article contains strong personal opinions and beliefs; I do not in any way intend to be offensive, but some of these ideas just might be worth a try — by you — to see if you feel the same way!

Attacking the mindset

It’s commonly believed that Linux is ‘tough to use’. Sure, it’s different from what people who’re used to Windows are accustomed to — but it’s not tough. Once you adjust to the differences, you’ll probably laugh at this misconception yourself, and tell others how wrong their perception is!

Just consider the many computer science students who’ve been inspired by the buzz that Linux has been creating over a long time now. They have resolutely set about learning how to use it on their own initiative — asking questions on mailing lists, forums and over IRC channels. Within a couple of weeks, they are ready to do more than just get around. Often, within a month, they’re so much at home with Linux that they begin introducing others to the OS. Astounding? It may seem so — but it’s just that those students were determined to explore and learn, and ignored the cries of, “It’s tough.”

There is always a learning curve involved whenever one is acquiring a new skill, and Linux is no exception. If students are taught to use and program on Linux, they will not just learn, but will also find it simple. It would just seem natural to them — learning something that they did not know earlier. “Linux is tough” is a modern-day myth that has to be busted. If you are an educator, please do your bit. You are the one that students look up to, and if you show them the right way, they will follow your example.

Getting Linux up and running

Okay, once you have decided to use Linux, how do you go about it? You may have heard of lots of different Linux “distros” (also called distributions): Ubuntu, Fedora, Debian and more. Why so many “Linuxes”? Let me explain. Technically, “Linux” is the name of a kernel (for more information, refer to this Wikipedia article, or the official home of Linux). Since a kernel is of little use on its own, user-space tools from the GNU project (including the most common implementation of the C library, a popular shell, and many common UNIX tools that carry out many basic operating system tasks) were combined with the Linux kernel to make a usable operating system. The graphical user interface (or GUI) used by most Linux systems is built on top of an implementation of the X Window System. Different free software projects and vendors build different combinations of packages and features, to provide varying Linux experiences to different target audiences — thus resulting in myriad Linux distributions.

So which Linux distribution should you use? Ubuntu and Fedora both have individually made the Linux experience very user-friendly for casual users of the computer — for Internet surfing, e-mail and document processing needs. Either of these is ideal for you to get started with.

Linux installation can be somewhat tricky, though, especially if you intend to set up a dual-boot system where you can boot either Linux or your old Windows. Otherwise, it’s quite simple: download the CD (ISO) image, burn it to a disc, boot your computer from it, and let it install! The best way to do a dual-boot set-up the first time is to get hold of someone in your school, locality or office who knows about it, and ask them to guide you.

Also, there are other options if you want to try Linux either without installing it, without replacing Windows or doing a dual-boot set-up. See the Dealing with practicalities section towards the end of this article, for some of these ideas.

The Ultimate Linux Newbie Guide is a good reference to help you learn things yourself. With Linux, an experimental approach to learning helps a lot. So, back up your data, and get started with those install discs if you can’t find anyone to help you out. These days, most Linux distributions come with just the essential applications and libraries installed — which probably won’t be sufficient for programming needs.

To enable easy installation of new software, most distributions have a package manager (in the Linux world, software is distributed in the form of “packages”), which you use to easily download and install new software from the Internet. The Ultimate Linux Newbie Guide is a good reference for this topic.

So that this article will be of maximum utility, I will try to be more general, and avoid favouring any particular distribution.

Choosing a text editor

We won’t be using an Integrated Development Environment (IDE), at least, initially. We will just do it the simple way: write code using a text editor, save it, and compile/interpret it using an appropriate compiler/interpreter. In the Linux world, you have a plethora of text editors to choose from. One of the editors, such as gedit or kwrite, will definitely be installed when you install Linux — you can use either. If you install a distribution like Ubuntu, which has the GNOME desktop environment, then you will have gedit already installed. It’s just like Notepad, only more useful and feature-rich.

C/C++ programming on Linux

C is usually the first language taught to many students in Indian engineering schools and colleges, so let’s first look at how we program in C on Linux. Note that the C code that you will write on Linux will be the same that you would write on Windows/DOS, as long as you are writing ANSI C code. Some library functions, such as those provided by conio.h and graphics.h, are not part of the ANSI standard. Hence, you won’t be able to use them on Linux.

The C compiler you use on Linux is GCC. It is part of the GNU Compiler Collection. Open a terminal and run the command: gcc. If you see something like the following output, it means GCC is already installed.

gcc: no input files

However, if you see something like “Command not found”, then you will have to install GCC using the package manager.

Besides a compiler, you will also need the C standard library, called glibc, to compile your C programs correctly. Type in locate glibc and check the output. If it shows directory structures of the form /foo/bar/glibc or the like, then you have glibc installed; else you need to install it.

Okay, now that we have confirmed the presence of a text editor, a compiler and the standard library, let us write our first code in C on Linux. For the purpose of this article, let’s create a sub-directory called ‘codes’ under your ‘home’ directory, in which we will store all our source code.

Start up gedit and input this simple C code to print the factorial of a number:

#include<stdio.h>
int main(int argc, char **argv)
{
    int n, i,fact=1;
    printf("Enter a number for which you want to find the factorial:: ");
    scanf("%d", &n);
    for(i=1;i<=n;i++)
    fact=fact*i;
    printf("Factorial of %d is :: %dn", n,fact);
    return 0;
}

Save this code in the codes sub-directory with the name fact.c. Launch your shell program (terminal), and run cd codes to go to this directory. Once you are there, issue the following command:

gcc factorial.c

After executing the command, run ls and you will see an a.out file in the current directory. This is the executable file of your C program, compiled and linked with the appropriate libraries. To execute it, run (note the leading ./, which is essential!):

./a.out
Enter a number for which you want to find the factorial:: 5
Factorial of 5 is :: 120

Congratulations, you have just written your first C program on Linux! That was just the normal C that you write on DOS or Windows — no surprises there! A bit more about this a.out file: This is the Linux equivalent of the .exe file that you would see under DOS/Windows; it is the executable form of your code. As you might have already guessed, this file cannot be executed on DOS or Windows, since it is in a different format.

Now, instead of having to rename your executable file each time you compile, you can specify the output file name to the compiler:

gcc -o factorial factorial.c

Try a few more programs from your C programming and data structures classes.

The C Programming Language is a well-known programming book by Brian Kernighan and Dennis Ritchie, which teaches you C programming with a strong Linux flavour. It would be a good idea to try the examples and exercise programs from this book to get a flavour of C programming on Linux.

Let’s now write our first C++ program on Linux. The cycle of coding, compilation and execution is very similar to that for C, except for the compiler we use, which is g++. Check if it’s already installed by running the command in a terminal, like we did for gcc. Next, use your package manager to check if libstdc++, the standard C++ library, is installed (if not, install it). Once both are installed, open up gedit and type this simple C++ program:

#include<iostream>
#include<string>
using namespace std;
int main(int argc, char **argv)
{
    string s1="Hello";
    string s2="World";
    cout <<s1+" " + s2 << "n";
    return 0;
}

Save this file as string-demo.cxx in the codes subdirectory.

Compile and execute the file:

g++ -o string-demo string-demo.cxx
./string-demo

Running the above command should output the following on the terminal:

Hello World

The C++ code you see is standard C++, with the .h omitted from the header files. C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .c++, .cp, or .cxx.

Let us now write a simple C++ program that uses classes:

#include<iostream>
using namespace std;
class Circle{
    float r;
    public:
    void init(float x) /* Inline function */
    {
        r = x;
    }
    float area();
};
float Circle::area()
{
    return 3.14*r*r;
}
int main(int argc, char **argv)
{
    float radius;
    Circle circle;
    cout << "Enter the radius of the circle:: ";
    cin >> radius;
    circle.init(radius);
    cout << "Area of the Circle:: "<<circle.area()<<"n";
    return 0;
}

Save the file in the codes sub-directory as class-demo.cxx.
Compile and execute it:

g++ -o class-demo class-demo.cxx
./class-demo
Enter the radius of the circle:: 4
Area of the Circle:: 50.24

Assuming that you have been able to compile these programs successfully, I would now recommend you go ahead and write, compile and test some of your C/C++ assignments and problems using gcc and g++. If you face any issues, you are most welcome to ping me.

Java programming on Linux

Java is perhaps the next most widely taught language in Indian schools and colleges after C/C++. The best part of Java programming on Linux is that you use the same tools that you would use on Windows — yes, the Sun Java Development Kit.

To install the JDK on Linux, download the installer for Linux from its official website.

Choose the .bin file, and not the *rpm.bin file, unless you know what you are doing. (The .bin file is the equivalent of .exe on Windows). Once the download is complete, in your terminal, cd to the directory where the file has been downloaded, and use the following commands:

chmod +x jdk-6u18-linux-i586.bin
./jdk-6u18-linux-i586.bin

The file names above might differ depending on the JDK version that you have downloaded. The first line makes the installer executable, and the second line executes it. The installer should start now, and you should see the “Sun Microsystems, Inc. Binary Code License Agreement”.

Accept the licence, and the extraction of the JDK should start. Once the installer has exited, you should see a new sub-directory named ‘jdk1.6.0_18’ inside the current directory. If you are familiar with Java programming on Windows, this should be easily recognisable. Inside this directory is the bin sub-directory, which has the Java compiler (javac), Java interpreter (java), and others.

With this, we are all set; let’s write our first Java program on Linux. Fire up gedit and write the following Java code, which shows the usage of an array of integers:

import java.util.Random;
class ArrayDemo {
    public static void main(String[] args) {
        int[] arr = new int[10];
        for(int i=0;i<10;i++)
        arr[i] = (new Random()).nextInt();
        for(int i=0;i<10;i++)
        System.out.println("Element at index " + i + "is::" + arr[i]);
    }
}

Save the code to a file ArrayDemo.java, then compile and run it as follows:

/home/amit/jdk1.6.0_18/bin/javac ArrayDemo.java
/home/amit/jdk1.6.0_18/bin/java ArrayDemo

Note the first two commands, where I have given the full path to the location of the javac and java executables. Depending on where you have extracted the JDK, your path will vary.

Running the second command should output the following in your terminal:

Element at index 0is:: 480763582
Element at index 1is:: -1644219394
Element at index 2is:: -67518401
Element at index 3is:: 619258385
Element at index 4is:: 810878662
Element at index 5is:: 1055578962
Element at index 6is:: 1754667714
Element at index 7is:: 503295725
Element at index 8is:: 1129666934
Element at index 9is:: 1084281888

So, this is how you can compile, run, test and debug your Java programs.

OpenJDK

An article about Java programming in an open source magazine would be incomplete without talking about OpenJDK. It’s good for you to be aware of this project. As you might have already guessed, it is a GPL-licensed open source implementation of the Java Standard Edition — i.e., the source code of the JDK that you are so familiar with, is also now available for your scrutiny, in case you don’t like something in the current JDK.

So, is this a different Java? No — you write the same Java code. You can install OpenJDK from your Linux distribution’s package manager (it may come pre-installed with some distributions). Installation instructions are available here.

Dealing with practicalities

Due to various reasons, deploying Linux lab-wide may not always be possible. In such cases, it’s a good idea to have a single Linux machine in the lab, acting as an SSH server; you can install the necessary SSH client software on other operating systems, which will enable connecting to the Linux machine remotely.

This machine should be of a relatively good configuration, depending on how many students will be using it for their coding and compilation — a dual- or quad-core CPU with 4 GB of RAM and a hard disk of at least 320 GB is a good idea. For Windows, Putty is a widely used SSH client. If writing the code on Windows and copying it to the Linux machine to compile and run, you will also need to download the pscp program from the site, which lets you copy files from the local machine to the Linux SSH server.

If you need a GUI session from the Linux server to be accessible on the Windows machine (for example, while doing GUI programming) then investigate the OpenNX server (to be installed on the Linux server machine) and the NoMachine NX client for Windows. A machine with the configuration given above should support around 10 user sessions before it starts slowing down. Fine-tuning the desktop manager (use a light one like LXDE or XFCE) and using lighter editors like GVim for writing code, is a good start.

Another option (which does not need a dedicated Linux server machine) is to install Linux in a virtual machine on your desktop. This could also prove useful on a home computer. VirtualBox is virtualisation software that, when installed on your Windows system, will allow you to create a virtual machine, inside which you can install Linux without disrupting your Windows installation. You will, of course, need some free disk space (8 GB or more) for the virtual machine’s disk file. You don’t need to burn the Linux installation ISO onto a CD in this case — you can simply instruct VirtualBox to use the ISO image file as a disc inserted in the CD-ROM drive of the virtual machine.

This is also a good way to practice installing Linux, and to see how easy it can be. For Ubuntu, in particular, there is Wubi which lets you install (and uninstall) Ubuntu like any other Windows application, in a simple and safe way, “with a single click”. The Ubuntu files are stored in a single folder in your Windows drive, and an option to boot Ubuntu is added to your Windows boot-loader menu.

However, hard-disk access is slightly slower than installation to a dedicated partition. If your Windows drive is very fragmented, the performance will degenerate further. Hibernation is not supported under Wubi. Moreover, the Wubi filesystem is more vulnerable to hard reboots (turning off the power) and power failures than a normal installation to a dedicated partition, which provides a more robust filesystem that can better tolerate such events.

In general, programming on Linux will also require a decent level of familiarity regarding working with shell commands. Get familiar with working with the shell. Try to minimise the use of the mouse :-)

Using your favourite IDE on Linux

If you have been using any IDEs for your development needs, it should be great news that two very popular IDEs — NetBeans and Eclipse — have Linux versions as well, and both of them support C, C++ and Java development. For GNOME-based Linux distributions, Anjuta DevStudio is another powerful IDE for C, C++ and Java (and other languages too). All three should be available in your distribution’s package manager.

To conclude this article, I would like to urge you to make an honest effort to embrace Linux for programming. It’s a much better world to be in. I would love to address any queries/concerns/comments/suggestions that you may have, regarding this article.

Resources
The author would like to acknowledge Edgar D’Souza, for “filling in” bits and pieces (during the editing) which made the article more complete.
Feature image courtesy: Fabrizio. Reused under terms of CC-BY-SA.
  • Pingback: Tweets that mention Write Your Next Program on Linux – LINUX For You Magazine -- Topsy.com

  • Pingback: Tweets that mention Write Your Next Program on Linux – LINUX For You Magazine -- Topsy.com

  • Hrusikesh Sahoo

    It’s a wonderful article for the beginners.I am a MCA fresh graduate student,from Bangalore.I will complete my degree,after one month.I did,lot of programing in Ubuntu.But,I don’t have idea about the graphical programing & how to make a server? You had already discussed above,how to established a Server in Linux.But,I didn’t understood clearly.Can you please ,tell me? Thank You to the writer.

  • Utsa

    the best consolidate article on… why linux…what linux..to how linux…. will surely encourage IT professionals who are working on windows for a long time.. to try and use something entirely new and different..

  • http://www.dhayfule.com Pravin Balaji Dhayfule

    Great to read article.

    I have switched over to Ubuntu since 2 years and find it more safe and robust as compared to windows. For those who are comfortable with VB and Basic like language, I would recommend GamBas which is FOSS alternative to VB (only on Linux not made for windows)

    BTW for the statement

    Either of these is ideal for you to get started with. Linux installation can be somewhat tricky, though, especially if you intend to set up a dual-boot system where you can boot either Linux or your old Windows. Otherwise, it’s quite simple: download the CD (ISO) image, burn it to a CD-R or RW, boot your computer from it, and let it install!

    Ubuntu had even made this simple through “Install within Windows” option that installs Ubuntu in dual boot mode for those who just want to get started with linux.

  • http://herupriadi.co.cc heru

    Thanks for ur information :)

  • Pranav

    really super article, after reading it, without any second thought i got Ubuntu Linux downloaded and installed. its really nice to use Ubuntu Linux.

  • http://Website pharmacy technician

    found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later

  • http://linuxforu sivabalan

    i want to know LINUX program

  • http://punuptech.com Anup

    Wonderful article. Keep it up

  • Kajal

    Really useful!

  • Chirag Chadha

    Great article for beginners….very useful….wish i had found it before i switched to linux….wud hav save much time and effort….

  • http://twitter.com/AbhishekAPatil Abhishek Patil

    Looking for some thing like this…
    Thank you sir….

  • Narasimha Murthy.Y

    Very good attempt ,its really very useful to beginners,congrats and keep it up

  • fabianwilliams

    I a C# dev looking at getting back into Linux, this was a very good article to get started thanks for doing it.

  • amitsaha

    Thank you for your kind comments everyone. I am glad it’s been of help.

    I am excited to announce my book: Write Your First Program, where I discuss C and Python programming on Windows and Linux. It’s meant to start from the basics of each language and cover topics needed to get started. See here: http://echorand.me/2013/05/16/new-book-write-your-first-program-c-and-python/ for more details.

  • Suhas

    Very helpful. Thank you.

  • Sogmeister

    Very helpful, thanks!!

  • Nnamdi (Educator)

    It really is a great piece. I’ve been trying to figure out most of what was put into this piece for a long while. Now it all falls into place. Much grateful for your effort. Please continue the good work.

  • Ly Chai Lon

    Yes, very helpful, Thanks ! I love linux and programming in Linux same as Ubuntu !

  • http://www.java-programming-tutorial.com/ Java programming tutorial

    Nice post. Covered both java as well as c/c++ programming on linux.

  • Gourav Dwivedi

    how to run and compile graphics program in c language like make a circle.line,ellipse etc……. in linux…..?? bcz give error graphics.h no find….??

All published articles are released under Creative Commons Attribution-NonCommercial 3.0 Unported License, unless otherwise noted.
Open Source For You is powered by WordPress, which gladly sits on top of a CentOS-based LEMP stack.

Creative Commons License.