Make your own free website on Tripod.com

Beginning Programming For Linux.

By: Martin Johnson

Contents:

Who should read this book

Getting started

Your first program

Input and output

Looping

Functions

Branching

Arrays

Character Arrays

Structs, Classes, and Unions

Pointers

Preprocessing

File I/O

Inheritance

Polymorphism

Opengl....

The linker

Your first opengl program

Moving your graphics

Adding interaction

Gtk+...

Your first Gtk+ program

Networking...

Your first socket program

Who should read This Book

This book is meant for people who run linux, and need to learn linux programming. This book is also be for any one who wants to learn programming in the linux environment. If you already know linux specialty programming of any kind I would suggest that you do not buy this book, because it would be a waste to you.

Getting started

First on getting started programming on linux, you should install a type of linux. I use Redhat linux, and I would recommend that you do the same. If you don't that's perfectly okay. The stuff in this book should work on any linux OS. If you are wondering where you can get linux, you can get it at linux.org. Some different distributions are mandrake, redhat, suse, slackware, debian, and many others. This programming may even be portable to BSD, UNIX, and with some slight alterations macintosh. Everything before Opengl is portable to all operating systems including windows. Also in getting started you should make sure that you have both gcc, and g++. If you don't, then get them.

Your first program

I am sure that if you have read the previous chapters that you are starving to learn some programming. Well to get started let me explain the parts of a C, or C++ program. First you have preprocessing this is what holds any thing preset like statements, and functions. Then you have main. This is the body of your program that actually does stuff. Then you have your statements, functions, expressions and your return code. Your return code just says what to return at the end of the program.

Well lets get on with it your first program looks like this.

#include <stdio.h>

int main(){

printf("Whats up\n");

return 0;

}

Lets look at this program. It's a C program, it includes the header file stdio.h which includes all the statements for standard input and output. then int main() which starts the body. Then a { which open up the function main. Next you have printf("Whats up\n"); this prints Whats up to the screen. printf stands for print formatted data. \n specifies to make a newline for new text, or what ever else. the ; end the function.

return 0; says that we are not returning anything from this program. The } says that the function main is over.

Now lets look at a C++ program

#include <iostream.h>

int main(){

cout<<"Linux is fun\n";

return 0;

}

In this program we include iostream.h which allows streaming input, and output. cout<<"Linux is fun is the equivalent to printf. Everything else is the same.

You compile these by typing gcc program.c -o name, or g++ program.cpp -o name

Input and output

Now we shall learn about taking stuff in, playing with it, and putting back out. There are many functions which allow us to to do this. In C we will use getchar, getc, and gets. In C++ we will use cin, cin.get, and cin.getline. These all get information from the user. In this chapter will also discuss ways of putting it out. Such as cout.fill, and cout.width. Also puts, putc, and putchar. Lets get started with some examples.

#include <stdio.h>

int main(){

int a, b, c;

printf("Enter a number: ");

a=getchar();

printf("Enter another #: ");

b=getchar();

c=a+b;

printf("%i, and %i = %i\n", a, b, c);

return 0;

}

This Makes 3 integer variables with the use of int. Then using getchar we get the variables from the user. Then we display them using printf. The %i stands for integer. We use this to tell the computer to display an integer. We say what %i is what by separating them by commas after the text, in order.

There are other ways of displaying, and getting data. If we were getting single characters we would use getc. If we chose to we could use puts instead of printf. That would look like this.

puts("Enter a #: ");

int a=getchar();

puts(a);

That bit of code would ask for a number. Then take a number, and then display the number entered. if the number was only one digit. We could say putc(a);

to display the number. Lets look at a C++ example.

#include <iostream.h>

int main(){

int a, b, c;

cout<<"Enter a #: ";

cin>>a;

cout<<"Enter another #: ";

cin>>b;

c=a+b;

cout<<"Your number is "<<c<<endl;

return 0;

}

Adding on to your knowledge of C++. You display extra characters, and strings by using the << operator. The >> operator takes in data. This is used in cin.

cin is being used to take in data. Also endl is new endl end the line of text in a cout. It is different from \n, because it terminates the line, and \n makes a new line. for example cout<<"Hello\n"<<"Martin\n";

would display

Hello

Martin

cout<<"Hello"<<endl<<"Martin\n";

would just display Hello.

Another data Type. Here is a new data type for you to use. it's called

char it stands for character. The variable type char specifies that what ever you type in is not a number, but text. Lets see an example of it.

#include <stdio.h>

int main(){

char a;

printf("Enter a Letter: ");

a=getc(stdin);

putc(a);

return 0;

}

This example takes in a single character, and displays it. stdin specifies that it is standard input. Lets see a C++ example.

#include <iostream.h>

int main(){

char a;

cout<<"Enter your first initial: ";

cin.get(a);

cout<<"The first letter of your first name is: "<<a<<endl;

return 0;

}

In this example you see how to use char in C++, and a new way of taking in data. This new way is cin.get. The function cin.get is used for taking in characters.

Looping

In this chapter you will learn something which will make your programming life much easier. Looping allows you to do a process a certain number of times. for

is one of these statements it lets you specify how many times a process should run. Another is while it lets you tell the computer to do something as long as an expression is true. There is one more it is called do, or do while. It allows you to do a process, or processes until something happens. Lets see a C example of a for loop.

#include <stdio.h>

int main(){

int x;

printf("How many hello's?\n");

x=getchar();

for (int y=1; y<=x; y++){

printf("hello\n");

}

return 0;

}

This example takes in a number, and then puts hello to the screen that many times. The for loop makes a variable, and gives it a value. Then it needs an expression for what that variable has to count to. Then you specify what to count by. The expression y++ is the same as y=y+1 every time the loop comes around. Here is a C++ example.

#include <iostream.h>

#include <iomanip.h>

int main(){

cout<<setw(15)<<"Counting by 10's to 100\n";

for (int g=1; g<=100; g+=10){

cout<<g<<"\t";

}

return 0;

}

This program counts by 10 to 100. Here I decided to add stuff. One thing is iomanip.h. It stands for input output manipulation. It allows us to say setw, setw lets us set the width, or number of spaces in a cout statement. In the example we place 15 spaces in front of Counting by 10's to 100. Also in the example we have \t. It is implemented like \n, but it places 5 spaces. It needs no spacial header. Lets get started on the while loop. It looks like this.

#include <stdio.h>

int main(){

char s;

while (s !='q'){

printf("Enter a character: ");

s=getc(stdin);

printf(%c\n", s);

}

return 0;

}

This program takes in a single character, and displays it until q is entered. The operator != means not equal to. So while s is not equal to q the program loops. Lets see a C++ example.

#include <iostream.h>

int main(){

double p, r, t, i, l=0;

cout<<"Enter your principle: ";

cin>>p;

cout<<"Enter your rate: ";

cin>>r;

cout<<"Enter your time: ";

cin>>t;

while(l<=t){

i=p*r*t;

cout<<i<<endl;

return 0;

}

This program figures simple interest for a certain number of years. It introduces new concepts such as double. The double specifies a variable the same as int, except double allows you to use decimals, as well as integers. The float data type is in essence the same as double. Lets see the do while loop.

#include <stdio.h>

int main(){

int a=0;

do{

printf("%d\n", a);

a++;

}while (a<=20);

return 0;

}

This shows counting from 1 to 20. %d is the same as %i, but it works on all numbers, and it is made for double. this program does adding while a<=20. This is fairly self explanatory. Lets see it in c++.

#include <iostream.h>

int main(){

int a=0;

do{

cout<<a<<endl;

}while(a<=20);

return 0;

}

In essence this is exactly the same.

Functions

Here is something else which may make your life a million times easier when your programming. Functions are like printf, or getchar(). They do something. In this chapter you will learn how to make your own functions. When you make a function, you declare it, and it's arguments(the things in parenthesis). Then you define it. This makes your life alot easier by say making a long math equation into one function instead of having to rewrite the equation everytime you want to use it. Lets see a C example.

#include <stdio.h>

float interest(float p, float r, float t);

float interest(float p, float r, float t){

float i;

i=p*r*t;

return i;

}

int main(void){

float p, r, t, i;

printf("Enter your principle: ");

scanf("%f", &p);

printf("Enter your rate: ");

scanf("%f", &r);

printf("Enter your time: ");

scanf("%f", &t);

i=interest(p, r, t);

printf("Your interest is %f\n", i);

return 0;

}

Here you learned some new things, you saw how to make a function, and no it is not necessary, that you declare it, you can just define it. Also you learned scanf. You use scanf to scan for numbers. getchar is improper for this. You use scanf by first typing in quotes the % of your variable %f specifies float. Then you say &variable, to specify which variable you are assigning a value. You also saw a new return code. The return code allows you to return a value from the function. we were returning i. The return code is not absolutely necessary. Lets see a C++ example.

#include <iostream.h>

void line(char ch, int l){

cout.width(l);

cout.fill(ch);

cout<<"\n";

}

int main(void){

line('=', 10);

return 0;

}

This example shows how you don't have to have a return code, or a declaration. Also something I forgot to mention. Anytime you have something with out a # sign in front of it above main, you should have the void argument to main. There are some extra output functions here. One is cout.width, this specifies how many of the cout.fills to make. The cout.fill specifies what to fill it with. If you haven't guessed what this example does it makes 25 equal signs.

Branching

Now we will add some user friendliness to our programs. Here we will cover if and switch. These allow you to make cases like just in case this happens, and if so like if this happens do this. These make your programs easier to navigate. Lets see a C example.

#include <stdio.h>

int main(){

int ch;

printf("1. Say hello\n");

printf("2. Say go away\n");

printf("Enter your choice: ");

ch=getchar();

switch(ch){

case 1:

printf("hello\n");

break;

case 2:

printf("go away\n");

break;

default:

printf("1 or 2 please!\n");

break;

}

return 0;

}

In this example we ask for 1, or 2. Then we say allow the user to switch between case 1, and case 2. So we learned that switch enables cases. Also we learned how to use case to specify what case it is. Then we learned to use break to specify the end of the case. Then we learned how to make a default, so that if they don't press 1, or 2 it gives them a different message. Lets see this in C++.

#include <iostream.h>

int main(){

char ch;

cout<<"press a, or b\n";

cin.get(ch);

switch(ch){

case 'a':

cout<<"You pressed a.\n";

break;

case 'b':

cout<<"You pressed b\n";

break;

default:

cout<<"a or b please\n";

break;

}

return 0;

}

In this example you saw how to use letters instead of numbers for you cases by using char. Remember when using char place your letters in single quotes.

Now we will see an if and else example. Here is one in C.

#include <stdio.h>

int main(){

int age;

printf("Enter your age: ");

if (age<2){

printf("You are a baby\n");

}

if (age>=2 && age<5){

printf("You are a toddler\n");

}

if (age>=5 && age<=12){

printf("You are a kid\n");

}

if (age>12 && age<20){

printf("You are a teenager\n");

}

if (age>=20 && age<60){

printf("You are an adult\n");

}

if (age>=60){

printf("You are a senor citizen\n");

}

return 0;

}

This program asks for your age, and then gives your classification. We do this by saying if(expression), and then giving instructions. If you were to make a default, you could do it like this.

if(name=="martin"){

printf("Hello martin");

}

else{

printf("I don't know you\n");

}

else would be your default.

From now on, I am not going to give 2 examples, because everything in C is the same in C++, and visa versa until we discuss file I/O.

Arrays

In this chapter we will talk about the concept of arrays. An array is a variable, which can serve as many variables in the computers memory. Arrays are useful for such things as sorting. Arrays are also useful if you have a program in which you do not know how many variables that you may need. An array is defined by typing in the type like int, double, char, float what ever and [# of variables]. Lets see an example.

#include <iostream.h>

#include <iomanip.h>

#include <stdlib.h>

int main(){

int s;

cout<<setw(15)<<"Grading program\n";

cout<<"How many grades do you wish to enter?: ";

cin>>s;

int g[s];

for (int l=0; l<=s; l++){

cout<<"Enter grade: ";

cin>>g[l];

}

system("clear");

for (int x=0; x<=s; x++){

cout<<x<<setw(5)<<g[x]<<endl;

}

return 0;

}

In this example we asked how many grades to enter then we made an array with that many grades, and then we asked for them. Then we cleared the screen, and printed them. When we call an array we say the letter and it's number that we are calling. Remember arrays start with the number zero. We also learned another header stdlib. stdlib allows us to use the system command, system allows you to execute command line programs. If you did not know clear, clears the screen on a linux system.

Character arrays

Character arrays are used the same way as other arrays, but they allow us to get in strings, or text. Now we will be working with words as well as numbers. Lets see a C example.

#include <stdio.h>

int main(){

char name[32];

printf("Enter your name: ");

gets(name);

printf("hello %s\n", name);

return 0;

}

In this example we asked for a name, and then said hello and then the person's name. When we did this we made a character array of 32. This means that the person's name must be 32 characters, or less. The gets function stands for get string it allows us to get multiple characters at once. The %s stands for string it is used to display strings, or text only.

Structs, Classes, and Unions

Structs classes and unions are used to make multiple variables, arrays, or functions. Classes are C++. Structs are C, and so are unions. Lets see an example of a struct.

#include <stdio.h>

struct info{

int birth;

int year;

int age(int y, int b){

int a=y-b;

return a;

}

}person;

int main(void){

printf("Enter your year of birth: ");

scanf("%d", &person.birth);

printf("Enter current year: ");

scanf("%d", &person.year);

int a=person.age(person.year, person.birth);

printf("The person is %d years old\n", a);

return 0;

}

This program teaches you how to make, and use a struct. You may, or may not give the structure a name like info. You must at the bottom give a variable in which to call your variables, and functions. You call a variable by saying variable.variable. The dot operator is what you use to call it with. If you do not have a calling variable like person just a closing brace, and a semicolon Then you can't call the variables, but the functions can be called with out a preceding variable. Lets move on to classes.

#include <iostream.h>

class cool{

public:

void laugh();

void wave();

};

void cool::laugh(){

cout<<"hahahaha\n";

}

void cool::wave(){

cout<<"waving\n";

}

int main(void){

cool call;

call.laugh();

call.wave();

return 0;

}

This program is utterly useless, but it demonstrates how to use a class. You use it the same as a struct, but when you define a function you type in the type of function like void then the class name::function name() and then define it. Other differences are when you make a calling variable. In you main type class name and then the calling variable. Another difference is that you have to say weather or not your information is public meaning it can be transferred over to main, or other classes, or if it is private meaning it must stay with in functions inside the class. Lets move on to unions.

#include <stdio.h>

union{

char name[14];

}n;

int main(void){

printf("Enter your name: ");

gets(n.name);

printf("Whats up %s\n", n.name);

return 0;

}

Here we used a union. Unions are the same as structs, but they take up less ram, and need no name.

Pointers

Pointers are used to make variables pointed to there variables. They can also be used to point at, and manipulate memory addresses, such as that of your video card, or modem. Pointers can also be used so that you do not have to use character arrays. Lets see a few hunks of code that could be used.

char *a=0x12FFCeF;

char *a makes a pointer. This hunk of code points to memory address 0x12FFCeF. When you are done with a pointer just type delete pointer name;

like this:

delete a;

int *a=4;

int *b=8;

a->b;

this points a to b;

you renew a pointer by typing pointer=new pointer, and yes new is a key word.

You can also use pointers like this.

char *n;

printf("Enter your name\n");

gets(n);

I will explain pointers better when we discuss polymorphism.

Preprocessing

Preprocessing is making predefined macros. Preprocessing statements begin with a # sign like #include. Yes #include is a preprocessing statement. Some others are #define, #ifdef, and #endif. Lets see an example.

#include <stdio.h>

#ifdef MJ_H

#define MJ_H

#endif

This says that if the header mj.h is included define it. lets see some more.

#define PI 3.1415

This says that PI is 3.1415, this unlike a variable cannot be changed, and must be in all capital letters, where a variable can be lower case, capital, what ever. Also if this is above main where it goes it needs no calling variable. Lets see an example.

#define PI 3.1415

int main(){

cout<<3*PI<<endl;

There you have it no main(void), and no call.PI. You use preprocessing for making headers.

File I/O

File input, and output is very handy when saving information gotton from the user for later use. Here you will see both C, and C++ examples, because they are different. Now C is harder for this than C++, but learn them both because in the linux environment most things are done with C, and very few libraries use C++. So lets see a C example of a file reader.

#include <stdio.h>

enum {GOOD, BAD};

int main(){

FILE *f, *in;

char file[]="dictionary.txt";

int x=GOOD;

if ((f=fopen(file, "r"))==NULL){

printf("Failure\n");

x=BAD;

}

else{

int ch;

while(ch=fgetc(in)) !=EOF){

putchar(ch);

}

return x;

}

This example reads a text file and puts out it's contents. EOF is end of file, and == is the comparison operator, when using if. Just = gives it that value. NULL is empty, meaning either the text don't exist, or is empty. Lets see some writing.

#include <stdio.h>

int main(){

enum {GOOD, BAD};

FILE *f, *out;

char file[]="hello.txt";

int x=GOOD;

if ((f=fopen(file, "w"))==NULL){

printf("Failure\n");

x=BAD;

}

else{

fputs("Hello", out);

}

return x;

}

One more thing "w", means for write, "r", means for read. In file writing in C this is only a small fraction of everything doable, but I don't want the book to be that long. Lets see the C++ way of reading.

#include <iostream.h>

#include <fstream.h>

int main(){

char ch;

ifstream fin("dictionary.txt");

while(fin.get(ch)){

cout<<ch;

}

fin.close();

return 0;

}

Thats all it opens the text for reading, reads it, and then closes it. Lets see some writing.

#include <iostream.h>

#include <fstream.h>

int main(){

ofstream fout("hello.txt");

fout<<"hello\n";

fout.close();

return 0;

}

fout writes to a text like cout to the screen. Don't forget in any file writing to include fstream.h.

Inheritance

Inheritance, is allows one class to basically inherit another. This means that one class can use another's public information. Remember when we discussed classes we discussed public, and private information. Well in inheritance, you can inherit the public info, but not the private. There is another keyword like private which can be inherited it's called protected, it's the same as private, and thats the only difference. Inheritance is what part of OOP, or object oriented programming. If you did not know C is not object oriented, unless it's objective C. So you know we are talking about C++. In order to object orient, we have to make objects. An object is a function. When we deal with OOP, we make constructors, and deconstructors. A constructor, is a function with the same name as the class. A deconstructor is the same, but with a preceding ~. I will note place notes in this program so you know what I am doing as I go. You make comments, which don't affect your program by typing //your comment. Lets see an example.

#include <iostream.h>

class bank{

public:

bank(); //constructor

~bank(); //deconstructor

float account();

protected:

float balance;

private:

float interest;

};

class store: public bank{ //we just made class inheriting bank

public:

store();

~store();

enum {DELETE};

DELETE account();

};

Now you see how inheritance works. Now say that DELETE had a value of 0, then it could have made accounts value the same. This program does nothing. It is just an example of inheritance. I am sure if you played with it you could make a working program using inheritance.

 

 

Polymorphism

Polymorphism is another part of OOP. With polymorphism you use pointers to have one class make an object from the other. So if you inherit one class from another to inherited class can make a new object of the other class. Like this bank mbank=new store. Once you have done this you can use a pointer to invoke any member of the bank class. A member is anything in the class. Lets see an example to better improve your understanding.

#include <iostream.h>

class computer{

public:

computer(){}

~computer(){}

int mouse(){

//some definition}

char keyboard(){

//some definition}

};

class language: public computer{

language(){}

~language(){}

char c(){

//some definition}

char cpp(){

//some definition}

};

int main(void){

computer *mlanguage=new language; //calling variable

mlanguage->mouse(); //mlanguage invokes mouse function

mlanguage->keyboard();

return 0;

}

As you see polymorphism can be a powerful tool. I used the //'s to teach you as I went, in hopes that you may understand better. Remember polymorphism is OOP meaning it's not in C, but C++.

The linker

The linker is used to link libraries, and object files to program, even other programs if you are making a driver with a module. Thats not we will be using it for, we will be using to to only link libraries. These libraries are just the libraries used to compile an opengl program. Linking is not hard, you just type the -llibrary, when your compiling. So here is how you compile an opengl program.

g++ program.c -o name -lGL -lGLU -lglut -lm. I know it looks long here, but in reality it is realy not that bad, it feels like less each time.

Your first opengl program

Opengl stands for open graphics library. This means that you are jumping up and down saying I am going to learn how to make graphics. No this is not like the ms-dos qbasic graphics. These graphics are Gui's(graphical user interface) meaning that they are just like running an application such as ktron, or kedit. Except all these do is simple graphics. If your wondering how powerful opengl is, well lets just say it made quake, and doom. I am going to skip the 2d crap. Lets go straight to 3d, because it looks better, and it's easier to understand. First off everything you do in opengl is made in functions, like in the function chapter. Lets see and example.

#include <GL/glut.h>

void graphics(){

glClear(GL_COLOR_BUFFER_BIT); //enables color, and clears the screen

glColor3f(0, 1, 0); //sets the color of the forground RGB no red yes green no blue

glEnable(GL_LINES); //lets make some lines

glVertex2f(25, 0); //x, y coordinates of the lines start

glVertex2f(-10, 40); //x, y coordinates of it's end

glEnd(); //end GL_LINES

glFlush(); //allow graphics to execute

}

void bg(){

glClearColor(1, 0, 0, 1); //red background the fourth argument is the alpha

}

void window(GLsizei w, GLsizei h){

glViewport(0, 0, w, h); //set where you view the line from on the screen

glMatrixMode(GL_PROJECTION); //sets matrix for projection

glLoadIdentity(); //loads the matrix

glOrtho(-100*w/h, 100*w/h, -100, 100, -100, 100); //sets the x/y coords.

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

}

void main(void){ //main has to be void

glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB); //sets buffer for depth, and color

glutCreateWindow("line"); //make the window and name it

glutDisplayFunc(graphics); //display the graphics function

glutReshapeFunc(window); //set window proportions

bg();

glutMainLoop(); //hold window open until the user closes it

}

This program draws a line on the screen. Yes thats right no need for a return code. I suppose that my //'s made this program much more understanding.

Moving your graphics

Finally some animation. I know you have probably been wanting to learn how to do some something that moves since the last chapter, so here it is this chapter will teach you how to do some 3d objects, and rotate them. Lets see an example.

#include <GL/glut.h>

GLfloat a=0;

void graphics(){

glClear(GL_COLOR_BUFFER_BIT);

glColor3f(0, 1, 0);

glRotatef(25, a, a, a); //rotates at 25 degree angle along axis x, y, and z the z axis is for depth

glutWireCube(50); //makes a cube size 50 at point 0, 0

glFlush();

}

void timer(int val){

a+=1;

glutPostRedisplay(); //redisplay the screen

glutTimerFunc(60, timer, 1); //redew function every 60 milliseconds

}

void bg(){

glClearColor(1, 0, 0, 1);

}

void window(GLsizei w, GLsizei h){

glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

glOrtho(-100*w/h, 100*w/h, -100, 100, -100, 100);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

}

void main(void){

glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB);

glutCreateWindow("cube");

glutDisplayFunc(graphics);

glutReshapeFunc(window);

glutTimerFunc(60, timer, 1);

bg();

glutMainLoop();

}

If you did not know this program makes a rotating cube. There is a list of built in 3d objects like glutWireCube. Some are glutWireTeapot with the same arguments, and several others. The timer function decides the interval in which the program is refreshed.

Adding Interaction

In this chapter you will learn how to add keyboard, and mouse interaction into your programs. Lets get started with a mouse example.

#include <GL/glut.h>

GLfloat r=0, g=1, b=0;

void graphics(){

glClear(GL_COLOR_BUFFER_BIT);

glColor3f(r, g, b);

glBegin(GL_TRIANGLES); //Lets make a triangle

glVertex2f(40, 25); //x, y of triangle top

glVertex2f(20, 0); //x, y of triangle bottom left

glVertex2f(60, 0); //x,y of triangle bottom right

glEnd(); //End of triangle

glFlush();

}

void mouse(int button, int state, int x, int y){

if (button==GLUT_LEFT_BUTTON && button==GLUT_DOWN){

b=1;

}

}

void timer(int val){

glutPostRedisplay();

glutTimerFunc(60, timer, 1);

}

void bg(){

glClearColor(1, 0, 0, 1);

}

void window(GLsizei w, GLsizei h){

glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

glOrtho(-100*w/h, 100*w/h, -100, 100, -100, 100);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

}

void main(void){

glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB);

glutCreateWindow("mouse interaction");

glutDisplayFunc(graphics);

glutReshapeFunc(window);

glutTimerFunc(60, timer, 1);

glutMouseFunc(mouse);

bg();

glutMainLoop();

}

When you click the triangle goes from green to yellow. Also you can make the triangle 3 different colors if you make a glColor3f before every glVertex2f, if you were to make the triangle more 3d you could use glVertex3f and then the x the y and the z. Lets see a keyboard example.

#include <GL/glut.h>

GLfloat x=0, y=0, z=0;

void graphics(){

glClear(GL_COLOR_BUFFER_BIT);

glColor3f(0, 1, 0);

glRotatef(25, x, y, z);

glutWireTeapot(50);

glFlush();

}

void keys(int key, int x, int y){

if (key=='a'){

x+=1;

}

if (key=='s'){

y+=1;

}

if (key=='d'){

z+=1;

}

}

void timer(int val){

glutPostRedisplay();

glutTimerFunc(60, timer, 1);

}

void bg(){

glClearColor(1, 0, 0, 1);

}

void window(GLsizei w, GLsizei h){

glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

glOrtho(-100*w/h, 100*w/h, -100, 100, -100, 100);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

}

void main(void){

glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB);

glutCreateWindow("keyboard interaction");

glutDisplayFunc(graphics);

glutReshapeFunc(window);

glutTimerFunc(60, timer, 1);

glutKeyboardFunc(keys);

bg();

glutMainLoop();

}

This makes a wire teapot that when you press the a, s, or d key it rotates at 25 degrees along the selected axis. Well thats it for opengl now you will be making gtk+.

Your first GTK+ program

GTK+ is a GUI library. It is the library used to make the gnome desktop. GTK stands for gimp tool kit. GTK+ is C, not C++. When you make a gtk+ program you compile it like this.

gcc program.c -o name -lgtk -lgdk

Thats it for the linker, but the code takes longer to do than opengl. GTK+ is the most straight forward easy to understand library even though qt is faster to code, and the programs look better, gtk+ is still easier to understand, and can do all the same stuff, if not more. Another GUI library is Xlib, this library actually programs at the X server level, and it is like making C closer to assembly. In C you comment like this /*comment*/ rather than // I am teaching this in the later chapters, because in the earlier chapters some people may confuse them selves with //, and cout, and other output statements, also it is unnecessary. Well lets write this program.

#include <gtk/gtk.h>

void quit(Gtk *a, gpointer b){

gtk_main_quit();

}

int main(int argc, char **argv){

GtkWidget *top, *box, *label; //variables

gtk_init(&argc, &argv);

top=gtk_window_new(GTK_WINDOW_TOPLEVEL);

box=gtk_vbox_new(FALSE, 10);

label=gtk_label_new("Hello World!");

gtk_window_set_title(GTK_WINDOW(top), "Hello");

gtk_container_set_border_width(GTK_CONTAINER(top), 15);

gtk_widget_set_name(top, "nothing");

gtk_widget_set_name(box, "box");

gtk_widget_set_name(label, "label");

gtk_signal_connect(GTK_OBJECT(top), "destroy", GTK_SIGNAL_FUNC(quit), NULL);

gtk_container_add(GTK_CONTAINER(top), box);

gtk_box_pack_start_defaults(GTK_BOX(box), label);

gtk_widget_show_all(top);

gtk_main(); /* same as glut_Main_Loop();

return 0;

}

Well thats your example after all this time I am sure you can figure it all out.

Your first socket program

As you may have noticed this chapter is in the networking category, this so you may have already concluded that sockets have something to do with network programming. If you know basic electronics, you will know that sockets are used to make a connection, such as that of an electrical socket. In this chapter we are going to make a pair of unix/linux sockets, and connect them, once they are connected we will send messages between the two. Lets begin, note that these programs are compiled the same as the first examples, and that this is C, and g++ will not work for these particular examples to use gcc.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

#include <errno.h>

#include <sys/types.h.

#include <sys/socket.h>

int main(int argc, char **argv){

char msg1[5];

char *msg2;

int s[2];

int a, rec;

a=socketpair(AF_LOCAL, SOCK_STREAM, 0, s);

if (a == -1){

fprintf(stderr, "%s\n", strerror(errno));

return 1;

}

a=write(s[0], msg1="Hello", 5);

if (a<0){

printf("Crap operation failed\n");

return 2;

}

printf("%s was wrote by socket 0\n", msg1);

a=read(s[1], rec, sizeof rec);

rec[a]=0;

printf("socket 1 read from socket 0 %s\n", rec);

a=write(s[1], msg2="whats up", sizeof msg2);

printf("socket 1 wrote socket 0 %s\n", msg2);

a=read(s[0], rec, size of rec);

rec[a]=0;

printf("socket 0 read from socket 1 this message: %s\n", rec);

close(s[0]);

close(s[1]);

return 0;

}

Thats all.

Well Now that you have learned the essence of standard programming you have no need to learn more unless you would like to write more console applications, in this case get C++ Unleashed, or C Unleashed, or even get both. Hopefully you will wish to expand your opengl knowledge, and write games for linux, and then draw more people into our realm. You can do this by buying linux game programming. If you liked the little bit of GTK+ programming I showed you get Sam's Teach yourself GTK+ programming in 21 days. If you would like to learn QT instead get Linux programming unleashed. If you would like to expand your networking knowledge, which I suggest you do because it is a hot market right now for linux. Get Linux Socket Programming by Example. You may find these books on amazon.com, bn.com, or halfpricecomputerbooks.com.