CGI for C++ applications

Source Code

The hard part about this example is doing anything demonstrable with C++. So we'll do something very silly in just printing our HTTP output into the log file. For the kcgi inclusion, we'll need all the usual header files.

#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */
#include <kcgi.h>

Next, we'll need our C++ bits. This is make-work, but serves to illustrate…

#include <iostream>

Now let's just jump directly into our main function. It will do nothing more than print Hello, world! to the browser. But it will also emit Said hello! into the error log. See your web server configuration for where this will appear. It's usually in the error.log file. On OpenBSD's default server, it's often in /var/www/logs/error.log.

main(void) {
    enum kcgi_err er;
    struct kreq r;
    const char *const pages[1] = { "index" };

    /* Set up our main HTTP context. */

    er = khttp_parse(&r, NULL, 0, pages, 1, 0);
    if (er != KCGI_OK)
        return 0;
    khttp_head(&r, kresps[KRESP_STATUS], 
        "%s", khttps[KHTTP_200]);
    khttp_head(&r, kresps[KRESP_CONTENT_TYPE], 
        "%s", kmimetypes[r.mime]);
    khttp_puts(&r, "Hello, world!\n");
    std::cerr << "Said hello!";
    return 0;

Nothing to it—looks like any of our C examples. The difference is that we've used some C++ code to emit Said hello! to the error log. The next part is how we can compile this code. For that, we'll need to use a C++ compiler instead of the C compiler we've been using to date.

% c++ `pkg-config --cflags kcgi` -c -o tutorial5.o
% c++ -static -o tutorial5 `pkg-config --libs kcgi`

Or just… (and noting again the -static, which we need by being in our file-system jail)

% c++ -static `pkg-config --cflags --libs kcgi` -o tutorial5

Now you can install your compiled CGI script just like any CGI script. See Getting Started with CGI in C for these steps in detail. All of these steps work for FastCGI, of course. Enjoy! (On non-OpenBSD systems, you'll probably need to use sudo instead of doas.)

% doas install -m 0555 tutorial5 /var/www/cgi-bin