Tuesday, September 2, 2014

C code tidbits.

Just like there are many verbal languages for speaking i.e. English, Spanish, Italian or etc.,  computers have their own languages also. Most people understand a verbal language  without having to do any translation. For computers that can be different. So if you want to use a language on a computer, some translation will need to be done to convert the commands (aka source code) to the ones and zeroes a computer understands. This is called compiling. There are a zillion languages that can be used, but one of the most common is "C" pronounced "see". "C" was made famous by Dennis Ritchie and Brian Kernighan also know and K&R.


Even if you are not a programmer, you will get the urge to create your own program. This usually happens when you seen some code on a web page or in a magazine that you just have to try. So then every once in a while you may actually need to create a simple program either for testing a system or just to create a quick utility. Most systems support GCC (a c compiler) although you may have to install some programs. i.e. "sudo apt-get install  build-essential". Now let us create the world famous "HelloWorld" program for your system.

1. Create  or copy your source code into and editor such as vim, nano, joe, or etc. Be sure to save the file (aka source code) and then exit.   (source code is in the examples)

$ nano hw.c


Note: [code] and [/code] are not entered into the editor.

2. The you need to convert the source code to an executable program.

# $ gcc sourcecode.c -o executablename
$ gcc hw.c -o hw

3. Run or execute your program. (if no errors are detected otherwise changes will need to be made and then recompiled),

$ ./hw
Hello World!

Or if you want sort of a gui:

$ ./hw | zenity --text-info


Pat your self on the back as you have created your first program! That is all there is to it for simple programs you create. More advanced programs will require a bit more work. More about that later.
More  C source code is at: http://www.geekboots.com/c/intro.

Note: On simple programs that do not need libraries or whatever you can take a shortcut.

hw,c
[code]
 #include <stdio.h>
int main(void)
{
        printf("Hello, world.\n");
}
[/code]

$ make hw
cc     hw.c   -o hw

$ ./hw
Hello, world.

No comments:

Post a Comment