Question

I'm building this library, libmyproject.a I want it to include several other static libraries (libone.a and libtwo.a), so that the application that links with libmyproject doesn't have to link with libone and libtwo as well.

I'm new to the GCC chain. With Visual C++, I would just add all dependencies and it would create a lib which also includes all other libs that I want in it.

How can I accomplish this with GCC ?

A bonus question: I'm using scons to build, is there a way to tell scons to do this ? Right now it just ignores all the additional libs that I supply and only compiles the .cpp files into the library.

Was it helpful?

Solution

You have to use ar (binutils) for operations on archive files. I am using a simple Perl script to do the merging:

#!/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;

To invoke the script in 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])

Of course, you can merge libraries using Python function inside SCons. I prefer using a separate script, so it can be run from command line as any other build tool.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top