Apache Webserver is all written in ‘c’. So how does one develop using C++? Simple.
- Generate the stub in “c” using apxs tool (e.g.
apxs -n foo -g)
- use extern “C” in the module file to define the handlers that Apache would invoke.
- LoadFile is your friend which will load libstdc++.so
Here is a little more detail. Apache now comes with apxs tool that will generate a simple stub and with it compilation makefiles etc.
First I define Foo.h which contains a simple class implementation. For this howto I am keeping things simple by not splitting in multiple files. So here is Foo.h which only has the handler for incoming request and produces “Hello world from foo”.
Then I renamed the mod_foo.c to mod_foo.cpp and updated content. I declared a global object of Foo class. Again it could have been singleton but for now I simplified it. Important point to note is the use of
extern "C" at line 8 so the c++ compiler would generate names which are compatible with c. And I register my hook using a lambda which is not strictly necessary.
Next is to update the makefile to include CXX and CXXFLAGS for libtool to find them.
Now comes configuring apache to register the module and load necessary dependencies. This will allow you to visit /foo on your httpd webserver (e.g. http://theunixtips.com/foo) and see this code in action.
make reload would compile, install and bounce apache. Otherwise you can run these operations separately and upload the module to your apache installation. Now go ahead and start the browser and visit the page to see your code running in all its glory.