我想用 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
确实显示了一个 example_module
mod_example.so
中的符号。
什么给了?为什么 example_module
没有出现在我的 .so
中?我该怎么做才能修复它?
最佳答案
解决此问题的一种方法是将 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
关于c++ - 如何用 C++ 编写 Apache 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42605138/