【问题标题】:Merge multiple static libraries into one GCC scons将多个静态库合并到一个 GCC scons
【发布时间】:2011-05-14 10:07:10
【问题描述】:
我正在构建这个库 libmyproject.a
我希望它包含其他几个静态库(libone.a 和 libtwo.a),以便与 libmyproject 链接的应用程序也不必与 libone 和 libtwo 链接。
我是 GCC 链的新手。使用 Visual C++,我只需添加所有依赖项,它会创建一个库,其中还包含我想要的所有其他库。
如何使用 GCC 完成此任务?
一个额外的问题:我正在使用 scons 来构建,有没有办法告诉 scons 这样做?
现在它只是忽略了我提供的所有其他库,只将 .cpp 文件编译到库中。
【问题讨论】:
标签:
gcc
static
linker
scons
unix-ar
【解决方案1】:
您必须使用 ar (binutils) 对存档文件进行操作。我正在使用一个简单的 Perl 脚本来进行合并:
#!/usr/bin/perl
use warnings;
use strict;
use File::Temp qw(tempdir);
use File::Basename;
use Getopt::Long;
my %opt;
if (!GetOptions(\%opt,
"dest=s",
)) {
die "Invalid option!";
}
my $tempdir = tempdir( CLEANUP => 1 );
if (!chdir($tempdir)) {
die "Couldn't change directories to `$tempdir': $!";
}
foreach my $lib (@ARGV) {
my $subdir = $tempdir . '/' . basename($lib);
mkdir($subdir) or die "Unable to make $subdir: $!";
chdir($subdir) or die "Unable to cd $subdir: $!";
system("ar x $lib");
}
chdir($tempdir) or die "Unable to cd $tempdir: $!";
system("ar cr $opt{dest} */*.o") == 0 or die "'ar cr' failed: $?";
system("ranlib $opt{dest}") == 0 or die "'ranlib' failed: $?";
exit 0;
在 SCons 中调用脚本:
# this can be put to site_scons/site_init.py
def MergeLibs(env, target, sources):
"""Rapack multiple archive files into one."""
merge_libs_tool = os.path.join('$TOOLS_DIR', 'merge_libraries.pl')
lib = env.Command('${LIBPREFIX}' + target + '${LIBSUFFIX}', [merge_libs_tool] + sources,
'$SOURCE -dest ${TARGET.abspath} ${SOURCES[1:].abspath}')
return lib
# lib_one = env.StaticLibrary(...)
# lib_two = env.StaticLibrary(...)
# merged_lib = env.MergeLibs('myproject', [libone, libtwo])
当然,您可以在 SCons 中使用 Python 函数合并库。我更喜欢使用单独的脚本,因此它可以像任何其他构建工具一样从命令行运行。