如何用Autotools+Libtool为静态库添加-static后缀以区分共享库
Great question! When using Automake + Libtool to build both static and shared libraries across systems, you can tweak Libtool's configuration to append a -static suffix to your static library files—just like you do with CMake on Windows. Here's how to pull this off, with cross-system compatibility in mind:
1. Ensure Libtool is Properly Initialized in configure.ac
First, make sure your configure.ac sets up Libtool correctly. Use the LT_INIT macro (the modern replacement for AC_PROG_LIBTOOL) to enable both static and shared library support:
AC_INIT([your-project-name], [1.0.0]) AM_INIT_AUTOMAKE([-Wall foreign]) # Adjust automake flags to match your project needs LT_INIT([enable-static enable-shared]) # Explicitly enable both library types AC_PROG_CC # Use AC_PROG_CXX instead if this is a C++ project AC_OUTPUT([Makefile])
If you prefer to let your Makefile.am control static/shared builds per-library, you can omit the enable-static enable-shared arguments from LT_INIT and set those flags later.
2. Configure the Static Library Suffix
You have two flexible options here: apply the suffix globally to all libraries, or target specific libraries individually.
Option A: Global Suffix (All Libraries)
Add this line to your Makefile.am to apply the -static suffix to every static library in your project:
AM_LIBTOOLFLAGS = --static-suffix=-static
Option B: Per-Library Suffix
If you only want certain libraries to get the -static suffix, define the flag directly for that library in Makefile.am. For example, for a library named libfoo.la:
# Define your library target lib_LTLIBRARIES = libfoo.la libfoo_la_SOURCES = src/foo.c src/bar.c # Replace with your actual source files # Enable both static and shared builds for this specific library libfoo_la_LIBTOOLFLAGS = --enable-static --enable-shared # Append the "-static" suffix to the static library variant libfoo_la_LIBTOOLFLAGS += --static-suffix=-static
3. Build and Verify
Run these commands to regenerate your build files and test the setup:
autoreconf -vfi # Generate configure script and Makefile.in ./configure # Configure the project for your system make # Build the libraries
After building, you'll get the expected output across systems:
- On Unix-like systems:
libfoo.so(shared library) andlibfoo-static.a(static library) - On Windows (MinGW/MSYS2):
libfoo.dll(shared library) andlibfoo-static.lib(static library)
Key Notes
- Libtool Version Check: The
--static-suffixflag is supported in Libtool 2.2 and newer. If you're using an older version, you'll need to upgrade Libtool to use this feature. - Clean Old Builds: If you've run
configurebefore, runmake distcleanfirst to clear cached Libtool settings and avoid conflicts with old configurations. - Cross-Platform Auto-Handling: Libtool automatically manages system-specific file extensions (
.a/.lib), so you don't need to hardcode them—just the-staticsuffix itself.
内容的提问来源于stack exchange,提问作者Isaac Monteiro

