Ubuntu FAQ: Compiling your first C or C++ programs

2017-01-10  Source: Original Site  Category:Ubuntu  Views:149 

Advertisement

So you're willing to write your own C or C++ programs, or simply compile someone else's code? This guide will get you started...

This FAQ assumes you're trying to compile error-free code. To actually learn the C or C++ languages, see the How to start programming (http://ubuntuforums.org/showthread.php?t=333867) thread.
If you encounter compilation problems, you may want to check this thread: Troubleshooting common C and C++ compilation errors (http://ubuntuforums.org/showthread.php?t=691451).

0. Make sure the build-essential package is installed

This package installs the essential tools needed to build C and C++ programs. Don't try to install individual tools by yourself, experts made that package for a good reason...
sudo apt-get install build-essential

1.a Compiling your first C program

Copy & paste this code into a new file. Save the file as main.c
#include <stdio.h>

int main()
{
printf("Hello World!\n");
return 0;
}
Open a terminal, go to the directory where you saved main.c, and type:
gcc main.c -o testIf all went fine, nothing is printed and you get back to the shell. Now, run it:
./test"Hello World!" gets printed in the terminal.

Explanations: gcc is the C compiler
obviously, main.c means that the compiler must compile this file. If you want to compile several source files into a single executable, just list them all here.
-o test means "output the result of the compilation to an executable file named test". If this part is omitted, the executable will be named a.out by default.
./test runs the newly compiled executable. The ./ is needed because of the way the shell works (the current directory . is not in the PATH by default).

1.b Compiling your first C++ program

Most of what I just said regarding the compilation of C programs also apply to C++ programs.
The two main differences (besides the language itself) are:
g++ is the compiler that you must use.
you should use a .cpp file extension rather than a .c one
#include <iostream>

int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
g++ main.cpp -o test
./test

2. Paranoid programming is good for your health!

Many beginners want to avoid compiler errors and warnings at any cost, which often leads them to ignore the "cryptic" messages the compiler outputs and to tinker anxiously with the relevant line until the error goes away.
Don't fall in that trap! The compiler is your friend, the messages it outputs are kind advices rather than punishments. You should really take the time to try and understand those messages, this is a very good way to improve your code's quality.

As a matter of fact, most seasoned programmers set the compiler's warning level as high as possible, so that it catches the little errors they make when they aren't paying much attention.

Here are a few command line switches to enable some warnings and language features (check the manual for detailed information): -std=gnu99 (C only) enforces the latest C standard (1999), plus GNU extensions (must be explicitely specified)
-std=gnu++98 (C++ only) enforces the 1998 C++ standard (but the STL now supports most of C++0x TR1 anyway), plus GNU extensions (this is the default for C++ code)
-Wall enables most warnings (very useful)
-Wextra enables more warnings (very useful)
-Wwrite-strings warns when you misuse plain old C string constants (aka. deprecated cast from const char* to char*) (very useful) (see this discussion (http://ubuntuforums.org/showthread.php?p=4331515#post4331515) for more in-depth information)
-pedantic issues warnings when strict ISO compatibility is not met (the name says it all: pedantic, but it can be useful once in a while)
-Woverloaded-virtual (C++ only) warns when virtual functions are overloaded in derived classes (very useful)
-Weffc++ (C++ only) warns when some key point of Scott Meyer's Efficient C++ and More Efficient C++ books are not met (good practice)
-Wold-style-cast (C++ only) warns when you use old-style C casts in a C++ program (good practice, you should be using the new-style C++ casts)

3. Useful tips the -g flag instructs the compiler to include debugging information, so that you can debug your program with gdb itself or any gdb frontend.
sudo apt-get install manpages-dev to help you make sense of compiler warnings and errors.

4. Read the manual!

Plain old manpage:
man gcc

HTML version of the gcc manual:
sudo apt-get install gcc-doc
Once installed, point your browser to /usr/share/doc/gcc-doc/gcc.html

Thanks to so many people @UF for their very useful help, this FAQ wouldn't be the same without them (you know who you are ;)).

Related articles
  • Ubuntu FAQ: Compiling your first C or C++ programs 2017-01-10

    So you're willing to write your own C or C++ programs, or simply compile someone else's code? This guide will get you started... This FAQ assumes you're trying to compile error-free code. To actually learn the C or C++ languages, see the How to start

  • Ubuntu FAQ: Compiling and Running C# Programs 2013-01-08

    Working on the rest, post suggestions as well. I am not skilled or experienced in C# So you're willing to write your own C# programs, or simply compile someone else's code? This guide will get you started... This FAQ assumes you're trying to compile

  • Ubuntu FAQ: Compiling and Running Java Programs 2014-10-08

    Working on the rest, post suggestions as well. I am not skilled or experienced in Java So you're willing to write your own Java programs, or simply compile someone else's code? This guide will get you started... This FAQ assumes you're trying to comp

  • Ubuntu Please Post your First Impression of the NEW Dapper Release! 2015-04-18

    This is my first impressions of the NEW Dapper Release: 1. Basically the Ubuntu v6.06 CD is a "Live" CD & a "Full" CD. In Ubuntu v5.10 you had 2 separate CD's: "Full" CD & "Live" CD. When you boot from CD, you end up in a "Live" CD situation

  • Ubuntu What was your first experience with Linux like? 2012-01-16

    Posted by Rick Hamilton As humans, we experience “firsts” for almost everything in our lives. Having your first birthday, Getting your first car, Discovering your first true love…these are all experiences that are important to us, that we all cherish

  • Ubuntu What was your first "real" program? 2012-03-08

    What was your first useful program (or whatever) that someone did or might actually use? Or maybe it was just something you made that you were proud of becuse you didn't use a tutorial. I made several small programs before my venture into "real progr

  • Ubuntu What was your first &most recent music concert you attended? Which was your favorite? 2013-04-11

    What was your first &most recent music concert you attended? Which was your favorite? My very first concert was: BOC (Blue Oyster Cult); Houston, Texas. About 23 years ago. The most recent concert was: Rusted Root; Portland, Oregon. About 8 years

  • Ubuntu What is your first impression? 2014-04-24

    I was hoping to get some response on what your first impression is when you read: client.alive You may be wondering why I am asking this and you may have some ideas of your own. It isn't that I'm not willing to tell what that reason is - it's just th

  • Ubuntu What was the first serious thing you programmed? 2014-04-03

    A slight deviation from this thread (http://ubuntuforums.org/showthread.php?t=450459) :) What was the first serious thing you programmed, i.e. not for training or learning purposes but perhaps your first job or first project? Of course if you have ne

  • Ubuntu What was your first Linux experience? 2014-05-28

    My very first experience with Linux was a Knoppix LiveCD that my dad had. We only booted into it twice I think (I was 10, 5 years ago). I thought the desktop was really cool. My first real experience with Linux was Ubuntu 6.10 Edgy Eft. Surprisingly

  • Ubuntu What was your first "gaming" card? 2012-03-25

    My very first "gaming" video card was an S3 GENDAC 2MB VLB video card. This was back before Nvidia and even ATi. VLB cards were underrated. Back when PCI was just establishing itself as a form factor, my VLB was actually a little quicker than my firs

  • Ubuntu What was your first linux distro? 2013-02-19

    Mine was Yellow Dog Linux 6.2 on my PS3 and it almost turned me away from linux. You couldn't really do anything on it, and it more complicated to use than Ubuntu. Also setting up wireless internet was the biggest pain.

  • Ubuntu What was your first distro? 2013-04-10

    So what was your 1st distro? Mine was Puppy Linux.

  • Ubuntu Does compiling your own kernel actually make the OS faster? 2013-06-09

    Does compiling my own kernel actually make the OS faster? i just did that (using linux-source) and everything instantly became snappy.

  • Ubuntu What was your first programming book? 2014-08-09

    I'm really curious to see what linux users first programming books were. I started a topic on my blog about this and so far its all comments from windows users so some linux comments might help balance it out :) (Also my blog is CodeJustin.com (http:

  • Ubuntu What was your first programming language? 2014-11-30

    Inspired by the current slashdot poll. I am truly curious myself. For me, the first language I wrote a DECENT program in was ruby :), yeah, envy me, ruby! It wasn't to exciting, it was just a little rails app that searched a book database, but it was

  • Ubuntu What was your first portable digital audio player? 2013-06-29

    Just wondering, Mine was the Diamond Rio PMP300 back in 98, http://en.wikipedia.org/wiki/Rio_PMP300 I remember having a difficult time finding new music for it, other than what I ripped from CDs.

  • Ubuntu $80 off your first year with Dreamhost (website hosting) 2013-07-20

    lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam nisl. Phasellus eu erat et leo auctor accumsan. Pellentesque sollicitudin, eros condimentum lobortis pellentesque, urna enim rhoncus nisl, non ultrices nisi erat eu orci. Sed facilisis n

  • Ubuntu GCC compiling problem at a simple c++ program 2012-02-23

    I try to compile the simplest c++ program, called hello.c by gcc hello.c and the errors are: hello.c:1:21: error: iostream.h: No such file or directory hello.c: In function ‘main’: hello.c:3: error: ‘cout’ undeclared (first use in this function) hell

  • Ubuntu What was the first computer you started programming on? 2014-08-05

    For me, the very first was a TRS-80 pocket computer. My very first (non-trivial) program was a poker game program (in BASIC), however it quikly consumed the 1.2 kilobytes of RAM in the pocket computer. Then a little later when we got the TRS-80 Model