merge_static_libs.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import os
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. def _Usage():
  11. print 'Usage: merge_static_libs OUTPUT_LIB INPUT_LIB [INPUT_LIB]*'
  12. sys.exit(1)
  13. def MergeLibs(in_libs, out_lib):
  14. """ Merges multiple static libraries into one.
  15. in_libs: list of paths to static libraries to be merged
  16. out_lib: path to the static library which will be created from in_libs
  17. """
  18. if os.name == 'posix':
  19. tempdir = tempfile.mkdtemp()
  20. abs_in_libs = []
  21. for in_lib in in_libs:
  22. abs_in_libs.append(os.path.abspath(in_lib))
  23. curdir = os.getcwd()
  24. os.chdir(tempdir)
  25. objects = []
  26. ar = os.environ.get('AR', 'ar')
  27. for in_lib in abs_in_libs:
  28. proc = subprocess.Popen([ar, '-t', in_lib], stdout=subprocess.PIPE)
  29. proc.wait()
  30. obj_str = proc.communicate()[0]
  31. current_objects = obj_str.rstrip().split('\n')
  32. proc = subprocess.Popen([ar, '-x', in_lib], stdout=subprocess.PIPE,
  33. stderr=subprocess.STDOUT)
  34. proc.wait()
  35. if proc.poll() == 0:
  36. # The static library is non-thin, and we extracted objects
  37. for obj in current_objects:
  38. objects.append(os.path.abspath(obj))
  39. elif 'thin archive' in proc.communicate()[0]:
  40. # The static library is thin, so it contains the paths to its objects
  41. for obj in current_objects:
  42. objects.append(obj)
  43. else:
  44. raise Exception('Failed to extract objects from %s.' % in_lib)
  45. os.chdir(curdir)
  46. if not subprocess.call([ar, '-crs', out_lib] + objects) == 0:
  47. raise Exception('Failed to add object files to %s' % out_lib)
  48. shutil.rmtree(tempdir)
  49. elif os.name == 'nt':
  50. subprocess.call(['lib', '/OUT:%s' % out_lib] + in_libs)
  51. else:
  52. raise Exception('Error: Your platform is not supported')
  53. def Main():
  54. if len(sys.argv) < 3:
  55. _Usage()
  56. out_lib = sys.argv[1]
  57. in_libs = sys.argv[2:]
  58. MergeLibs(in_libs, out_lib)
  59. if '__main__' == __name__:
  60. sys.exit(Main())