Thursday, May 23, 2013

Introduction to GCC and G++


HelloWorld in C

Here is the classic HelloWorld program in C: (source file)
#include <stdio.h>

int main ()
{
  printf ("Hello World!\n");
}
Note:
  • The #include command is a preprocessor directive to load the stdio library.
  • Execution starts in a function (method) called main:
    • There are other signatures for main as we will see.
    • Although a return type is declared, nothing needs to be returned.
  • The printf method is used for screen output.
  • The "newline" character \n is explicitly required.
Compiling and executing on Unix:
  • The program above is a plain text file, as in any programming language.
  • The file extension needs to be .c.
  • The file name need not be helloworld.
  • To compile:
      gcc -o helloworld helloworld.c
      
  • This produces an executable called helloworld which can be executed as:
      helloworld
      
    or, if you don't have the current directory in your path:
      ./helloworld
    
    
    
    
    
    
    
    
    #include <iostream>
    
    int 
    main ()
    {
      std::cout << "Hello, world!\n";
      return 0;
    }
    
    The program can be compiled with the following command line:
    $ g++ -Wall hello.cc -o hello
    
    The C++ frontend of GCC uses many of the same the same options as the C compiler gcc. It also supports some additional options for controlling C++ language features, which will be described in this chapter. Note that C++ source code should be given one of the valid C++ file extensions ‘.cc’‘.cpp’‘.cxx’ or ‘.C’ rather than the ‘.c’ extension used for C programs.
    The resulting executable can be run in exactly same way as the C version, simply by typing its filename:
    $ ./hello
    Hello, world!
    
    
    
    
    $ g++ -Wall -c hello.cc
    $ gcc hello.o       (should use g++)
    hello.o: In function `main':
    hello.o(.text+0x1b): undefined reference to `std::cout'
    .....
    hello.o(.eh_frame+0x11): 
      undefined reference to `__gxx_personality_v0'
    
    Undefined references to internal run-time library functions, such as __gxx_personality_v0, are also a symptom of linking C++ object files with gcc instead of g++. Linking the same object file with g++ supplies all the necessary C++ libraries and will produce a working executable:
    $ g++ hello.o
    $ ./a.out
    Hello, world!
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    http://www.network-theory.co.uk/docs/gccintro/gccintro_54.html
    http://www.seas.gwu.edu/~simhaweb/C/lectures/module1/module1.html

No comments:

Post a Comment