2017-03-05 52 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