生成一个PHP扩展.so文件,一般就是这两种方法,第一种是在php源码内configure –[with|enable]-extension_name,然后make && make install,新扩展就会生成并保存在PHP的环境中了。

不过多半会有这种情况,我们跟别人共用一台开发机,开发机已经安装了标准的php开发环境,如果我们在用这种重新编译PHP的情况,如果我们有调试php源码,或者调试扩展,很有可能会损坏原有的标准环境,所以我们就需要另一种方法,只生成一个.so文件,然后把so手动放到标准环境下,就可以不影响大局了。

这种方式呢,也很简单,跟第一种方法一样,三步搞定。

一、phpize

进入你开发php扩展的扩展根目录,比如我想做的扩展是 fkhelloworld,目录在这里 /home/s/www/fukun/clang/php-5.2.6/ext/fkhelloworld.

在这里执行phpize,如果提示找不到此命令,就找到你php的bin目录,执行全路径的命令,比如我的phpize在这里:/home/s/apps/php-5.2.6/bin/phpize

If you look in the current directory at this point, you’ll notice a lot more files than you had there a moment ago. The phpize program combined the information in your extension’s config.m4 file with data collected from your PHP build and laid out all the pieces necessary to make a compile happen. This means that you don’t have to struggle with makefiles and locating the PHP headers you’ll be compiling against. PHP has already done that job for you.

phpize会结合你的config.m4文件中描述的信息以及你的php构建相关数据,制定合并所需的部分数据,这意味着你不必再在意makefile文件和定位要编译的php文件头,PHP已经把这些都做好了。

二、configure

第二部也很简单,在当前目录继续执行 ./congifure–[with|enable]-fkhelloworld, 如果出现错误:”configure: error: Cannot find php-config. Please use –with-php-config=PATH”, 那就是需要你手动指定php-config的路径,不过跟上一步的phpize路径类似,多写一个参数就可以了。有些注意的是,在这里configure的时候,不需要enable-debug 和 enable-maintainer-zts 参数,因为上一步的phpize都已经帮你做过了。

三、make

第三部就更简单了,直接执行make即可,然后观察输出,如果扩展有问题,会有相应的错误输出,一点一点的排查就ok了,如果一切ok,会有提示告诉你,扩展文件已经保存到当前目录的modules目录下了。

Libraries have been installed in:

/home/s/www/fukun/clang/php-5.2.6/ext/fkhelloworld/modules

到这里就基本ok了把,后边的使用大家在其它地方都能搜到,我就简单说下,把.so文件拷贝到php –ini所指定的extension_dir目录下,然后写个php测试文件,dl(‘fkhelloworld.so’),var_dump(get_loaded_extensions()); 看输出就ok了。

下边给几个图,是我写的一个扩展,生成一个函数fk_strpad,接受两个参数,一个字符串和一个整数,表明把字符串重复多少遍,最终返回。