2017-03-05 51 views
3

我想用C++编写一个Apache模块。我尝试了很准系统模块开始:如何在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确认没有在mod_example.so命名example_module符号。我发现这非常令人困惑,因为如果我手动

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

编译(模仿我看到里面apxs运行libtool命令),然后objdump -t确实在mod_example.so表现出example_module符号。

什么给?为什么example_module出现在我的.so?我能做些什么来解决它?

+0

如何编译cpp文件到目标文件,然后将目标文件传递到apxs工具? – Ankur

+0

@Ankur太棒了,谢谢你的建议!如果你把这个作为答案,我会接受它;否则我会在一两天内自己写出来接受。 –

+0

Daniel做了@ Ankur的建议工作?如果是这样,请您可以添加关于如何这样做的说明。这可能会帮助我和其他追随你的人。谢谢。 – JulianHarty

回答

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 
+0

非常感谢。 – JulianHarty