How You Build a C++ cgi script.

Sample c++ cgi script


Background

I have been using PHP and perl to create common gateway interface (cgi) scripts for many years. I never had a need to make a cgi script in c/c++ until recently. Some developers are driven to c++ cgi for speed reasons because compiled c++ is much faster than interpreted php or perl. My reason for exploring this now was a little different. I needed to make a script that would run on a standalone linux PC that has a web server but no scripting languages such as php or perl. Therefore, I Googled c++ cgi and was disappointed that I didn't find any examples that show how to create a c++ cgi in the same style often used by php and perl developers. Specifically, my goals for the script format were the following: 1) script must call itself 2) script must accept input via an html form 3) script must be able to parse the data provided in the form.


Materials

Instructions

More details are provided in the text below.

Sample script

Compile

C++ cgi scripts must be compiled to prepare them to be used. Unfortunately, this may present a problem if you do not have a shell/terminal account on the server. These accounts are more rare now due to security precautions but were the norm a decade ago. If you do not have a shell account, you may still be able to compile the script on the same hardware and software if you know what your host is using. Some of the references that I mention in the Bibliography section at the end of this article provide some details on this. Assuming that you have a shell account or your own server, you can compile your script with the command shown below.
sudo g++ -o cpp_cgi_example.cgi cpp_cgi_example.cpp

Copy file to cgi-bin directory

The destination for your cgi script will vary based on the web server that you are using. If you have an ftp account with a major web hosting company, you are often provided a directory "~/cgi-bin" where ~ is a shortcut to your home directory, which is probably something like /home/kevin or /home/howyoubuildit.
cp cpp_cgi_example.cgi /usr/lib/cgi-bin/cpp_cgi_example.cgi

Bibliography

Conclusion

I hope you found this useful. I am a creature of habit and have been using PHP and perl with this format for many years and it took me a little while to figure out how to duplicate that in c++ cgi. The references that I listed were a great help to me in my efforts. In particular, the link at http://www.trafficg.org/code_c/hello_var.shtml was most helpful.