Getting started with CGI programming with C++

I have been wanting to do some CGI programming using C++ however one thing or the other has got in the way. Today, I’ve got my head down to do a simple example which I’ve decided to share with you all. So here it goes…

If you haven’t already, first you have to configure Apache to execute CGI script. In your main Apache configuration file add the following…

<Directory /usr/local/apache/htdocs/somedir>
        Options +ExecCGI
        AddHandler cgi-script cgi pl
</Directory>

AddHandler tells Apache which are cgi files. In this case, extension with cgi or pl are considered as cgi files.

Before we start, here is my directory structure
1./ include – directory contains all header files
2./ library – directory contains all external libraries you may want to use
3./ source – directory contains all your source files
5./ resource – directory contains all your resources

Implementation
1./ Open include/hello.h using your favourite editor

#ifndef HELLO_H
#define HELLO_H

class Hello {
public:
	void hello (const char * name);
};

#endif

2./ Now open source/hello_fn.cpp

#include <iostream>

using std::cout;
using std::endl;

#include "hello.h"

void Test::hello (const char * name) {
  cout << name << endl;
}

3./ Open source/hello.cpp

#include <iostream>

using std::cout;
using std::endl;

#include "hello.h"
 
int main()
{
	Hello h;
	cout<<"Content-type: text/html"<<endl<<endl;
	cout<<"<html><body>"<<endl;
	h.hello("Hello World!");
	cout<<"</body></html>"<<endl;
 
	return 0;
}

4./ Lets run the code, you can use

 gcc -Wall -Iinclude/ source/*.cpp  -lstdc++ -o hello.cgi

or

 g++ -Wall -Iinclude/ source/*.cpp -o hello.cgi

5./ And then call hello.cgi on your browser (ie http://localhost/cgi-bin/hello.cgi, assuming you have called your cgi folder cgi-bin)

And there you have it and more soon.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s