link 带有 autotools 的库的正确方法

proper way to link a library with autotools

我需要 link libmagic 到我使用 autotools 构建的项目。

我目前的解决方案是:LIBS+="-lmagic" in configure.ac

但我认为更合适的方法是在 configure.ac 中使用 PKG_CHECK_MODULES 宏,在 Makefile.am 中使用 LDADD = @MAGIC_LIBS@,不幸的是,这不起作用.

这是我从 ./configure

得到的
configure: error: Package requirements (magic) were not met:

No package 'magic' found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

我认为这与pkg-config中缺少libmagic有关, 有什么想法吗?

您需要 libmagic 的 pkgconfig 文件。如果你的 PKG_CONFIG_PATH 中没有 magic.pc,你必须编写自定义 autoconf 宏来设置 MAGIC_LIBS.

I think that a more proper way to achieve this would be using PKG_CHECK_MODULES macro in configure.ac [...]

仅当您确实有 libmagic 的 pkg-config 数据文件时,即使这样 there is some controversy around PKG_CHECK_MODULES. As far as I can determine, the implementation you are probably using 也不会提供 pkg-config 文件。当然,您可以自己编写,但这会破坏目的。

如果您要依赖安装在标准位置之一的 header 和库——这是传统的并且非常合理的——那么配置构建的更惯用的方法是让 configure 测试他们的存在。例如,

AC_CHECK_HEADER([magic.h], [], [
  AC_MSG_ERROR([required header magic.h not found])
])
AC_SEARCH_LIBS([magic_open], [magic], [], [
  AC_MSG_ERROR([required library libmagic not found])
])

请注意,AC_SEARCH_LIBS() 会自动将 -lmagic 添加到 LIBS 之前。

通过提供 configure 选项,用户可以指定 header 和库的替代位置,您可能会变得更有趣,但这似乎不是您要找的东西,而且它似乎对 libmagic 来说太过分了。