如何在C ++中编写Apache模块?

时间:2017-03-05 06:14:16

标签: c++ apache apache-modules apxs2

我想用C ++编写一个Apache模块。我尝试了一个非常准确的模块来启动:

#include "httpd.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_request.h"

static void register_hooks(apr_pool_t *pool);
static int example_handler(request_rec *r);

extern "C" module example_module;

module AP_MODULE_DECLARE_DATA example_module = {
    STANDARD20_MODULE_STUFF, NULL, NULL, NULL, NULL, NULL, register_hooks
};

static void register_hooks(apr_pool_t *pool) {
    ap_hook_handler(example_handler, NULL, NULL, APR_HOOK_LAST);
}

static int example_handler(request_rec *r) {
    if (!r->handler || strcmp(r->handler, "example"))
        return (DECLINED);

    ap_set_content_type(r, "text/plain");
    ap_rputs("Hello, world!", r);
    return OK;
}

使用以下内容编译apxs似乎工作正常,

apxs -i -n example_module -c mod_example.cpp

但是,当我尝试启动httpd时,出现错误。我插入了一些换行符,使其更清晰。

httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf:
       Syntax error on line 1 of /etc/httpd/conf.modules.d/20-mod_example.conf:
       Can't locate API module structure `example_module' in file /etc/httpd/modules/mod_example.so:
       /etc/httpd/modules/mod_example.so: undefined symbol: example_module

确实,我可以通过objdump -t确认example_module中没有名为mod_example.so的符号。我发现这特别令人困惑,因为如果我用

手动编译
gcc -shared -fPIC -DPIC -o mod_example.so `pkg-config --cflags apr-1` -I/usr/include/httpd mod_example.cpp

(模仿我看到libtool内部apxs运行的命令),然后objdump -t确实在example_module中显示mod_example.so符号。

是什么给出的?为什么example_module出现.so?我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:2)

解决此问题的一种方法是将cpp文件编译为目标文件,然后将该目标文件传递给apxs工具。例如:

g++ `pkg-config --cflags apr-1` -fPIC -DPIC -c mod_example.cpp
apxs -i -n example_module `pkg-config --libs apr-1` -c mod_example.o