Páginas

domingo, 21 de julio de 2013

Hello World

How to say Hello World with style

Language C
 
#include <stdio.h> //Library for using standard input and output

int main(int argc, char* argv[]){ //function main which is executed first when the program is invoked
                                  //it receives 2 parameters, the first one is the counter of arguments
                                  //the second one is an array of arguments from command line

  printf("Hello world!\nby %s\n", argv[1]); //We say Hello and print the second parameter from char array argv[] of
                                            //arguments from command line

  return 0; //the function returns the integer zero and everything it's ok
}//End of the program 


In the command line above we see the next commands:

  • ls: List
  • gcc: It is used for compiling our code
  • ./ : For executing an executable

I am using a command line of GNU-Linux, if you do not know how it works I recommend to you learn about it. http://linuxcommand.org/learning_the_shell.php

In the worst case if you do not use GNU-Linux, you can download and install a distribution, for free!, I recommend Ubuntu. Trust me GNU-Linux looks more professional than windows, but also you can use Mac OS X.

For writing my code I have used Emacs, if you do not have it, you could download it easily. http://www.gnu.org/software/emacs/

In my case using the distribution Fedora:

$ sudo yum install emacs

If you have another distribution look this link: http://wikemacs.org/index.php/Installing_Emacs_on_GNU/Linux

After we have written our code in a file, in this case called helloworld.c, in a determined folder we can use ls command to list the files in our folder.

Before running our program we need to compile it, using:

$ gcc code.c

and it will generate an executable called a.out by default. If you want to personalize the name you can run the next line:

$ gcc code.c -o myname

and it will generate an executable called "myname".

Then, execute your program with:

$ ./a.out

or 

$ ./myname

If you do not give any parameter in this program you will see this:

Hello world!
by (null)

So, you can run as follow:

$ ./a.out MyName

or

$ ./myname MyName

It's up to you, this is not biblical.

Finally you will see:

Hello world!
by MyName


No hay comentarios.:

Publicar un comentario