macos 共享库的 Makefile?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/885451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:10:16  来源:igfitidea点击:

Makefile for Shared Libraries?

linuxmacosmakefileshared-libraries

提问by dwc

I've just written a Makefile to build a shared library, similar to the following:

我刚刚写了一个Makefile来构建一个共享库,类似如下:

libmystuff.so: CFLAGS+=-fPIC -shared
libmystuff.so: libmystuff.o otherstuff.o
    $(CC) $(CFLAGS) -o $@ $^

I like to avoid doing explicit actions when this seems like a common operation, but it seems there's no implicit rule or other built-ins to standardize this. I'm using GNU Make on Linux at the moment, but will need this to work on OS X as well.

当这似乎是一个常见的操作时,我喜欢避免执行显式操作,但似乎没有隐式规则或其他内置程序来对此进行标准化。我目前在 Linux 上使用 GNU Make,但在 OS X 上也需要它。

EDIT: I'm asking about make rules rather than compiler/linker flags.

编辑:我问的是 make 规则而不是编译器/链接器标志。

Can you recommend clean, reusable Makefile rules to build shared libs? Perhaps a %.so:or .c.so:type rule?

你能推荐干净、可重用的 Makefile 规则来构建共享库吗?也许是%.so:or.c.so:类型规则?

回答by ephemient

For portability, I'd look into integrating libtool.

为了可移植性,我会考虑将libtool.

define compile_rule
        libtool --mode=compile \
        $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
endef
define link_rule
        libtool --mode=link \
        $(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
endef

LIBS = libmystuff.la
libmystuff_OBJS = libmystuff.lo otherstuff.lo

%.lo: %.c
        $(call compile_rule)

libmystuff.la: $(libmystuff_OBJS)
        $(call link_rule)

install/%.la: %.la
        libtool --mode=install \
        install -c $(notdir $@) $(libdir)/$(notdir $@)
install: $(addprefix install/,$(LIBS))
        libtool --mode=finish $(libdir)

libtoolwill automatically add -fPIC/-DPIC/-sharedflags as appropriate, and generate whatever .o/.a/.sofiles would be used on the current platform.

libtool将会自动添加-fPIC/ -DPIC/-shared标志酌情而产生的任何.o/ .a/.so文件将在当前平台上使用。

Or you could use Automake's libtool integration.

或者您可以使用Automake的 libtool 集成。

回答by Artyom

Building shared libraries is platform dependent. For example, the flags you are using are ok for GCC for ELF platforms, for cygwin, for example, you do not add -fPIC for some other platforms and compilers you need other flags.

构建共享库取决于平台。例如,您使用的标志适用于 ELF 平台的 GCC,例如,对于 cygwin,您不需要为其他一些平台和编译器添加 -fPIC,您需要其他标志。

You need one of:

您需要以下其中一项:

  • Provide an option to set flags for user platform.
  • Use standard build system like Autotools
  • 提供为用户平台设置标志的选项。
  • 使用标准构建系统,如 Autotools