Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking a PHP Extension Written in C

Edit: Revising My Question

When building an external PHP module in C, how do I link shared objects?

like image 342
Blair Avatar asked Dec 04 '25 00:12

Blair


1 Answers

If your C extension code uses a shared library, you need to declare that in the config.m4 file.

I strongly recommend using the ext_skel script that's included in the PHP source to generate a skeleton config.m4:

./ext_skel --extname=myextension

Since you're linking to a library, by convention you should use the --with-myextension options (as opposed to --enable-myextension). Uncomment the relevant lines in the config.m4 and fill in the details of your lib.

Something like the following:

  # --with-myextension -> check for lib and symbol presence
  LIBNAME=the_lib_your_extension_needs # you may want to change this
  LIBSYMBOL=some_symbol_in_the_lib_you_extension_needs # you most likely want to change this 

  PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  [
    PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MYEXTENSION_DIR/lib, MYEXTENSION_SHARED_LIBADD)
    AC_DEFINE(HAVE_MYEXTENSIONLIB,1,[ ])
  ],[
    AC_MSG_ERROR([wrong $LIBNAME lib version or lib not found])
  ],[
    -L$MYEXTENSION_DIR/lib -ldl
  ])

Then to build it, run:

phpize
./configure --with-myextension
make

Finally you need to copy your module (or ln -s) to wherever your system expects to find it.

If that all worked then php -m should include your module in the list.

Unfortunately I've never found a good online reference to PHP's config.m4 commands - the books for this are Sara Golemon's Extending and Embedding PHP and also parts of George Schlossnagle's Advanced PHP Programming.

There's a reasonable beginners guide to creating PHP extensions by Sara Goleman here, but for the meat you really need her book.

like image 172
John Carter Avatar answered Dec 05 '25 14:12

John Carter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!