unixccompiler.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """distutils.unixccompiler
  2. Contains the UnixCCompiler class, a subclass of CCompiler that handles
  3. the "typical" Unix-style command-line C compiler:
  4. * macros defined with -Dname[=value]
  5. * macros undefined with -Uname
  6. * include search directories specified with -Idir
  7. * libraries specified with -lllib
  8. * library search directories specified with -Ldir
  9. * compile handled by 'cc' (or similar) executable with -c option:
  10. compiles .c to .o
  11. * link static library handled by 'ar' command (possibly with 'ranlib')
  12. * link shared library handled by 'cc -shared'
  13. """
  14. __revision__ = "$Id$"
  15. import os, sys, re
  16. from types import StringType, NoneType
  17. from distutils import sysconfig
  18. from distutils.dep_util import newer
  19. from distutils.ccompiler import \
  20. CCompiler, gen_preprocess_options, gen_lib_options
  21. from distutils.errors import \
  22. DistutilsExecError, CompileError, LibError, LinkError
  23. from distutils import log
  24. if sys.platform == 'darwin':
  25. import _osx_support
  26. # XXX Things not currently handled:
  27. # * optimization/debug/warning flags; we just use whatever's in Python's
  28. # Makefile and live with it. Is this adequate? If not, we might
  29. # have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
  30. # SunCCompiler, and I suspect down that road lies madness.
  31. # * even if we don't know a warning flag from an optimization flag,
  32. # we need some way for outsiders to feed preprocessor/compiler/linker
  33. # flags in to us -- eg. a sysadmin might want to mandate certain flags
  34. # via a site config file, or a user might want to set something for
  35. # compiling this module distribution only via the setup.py command
  36. # line, whatever. As long as these options come from something on the
  37. # current system, they can be as system-dependent as they like, and we
  38. # should just happily stuff them into the preprocessor/compiler/linker
  39. # options and carry on.
  40. class UnixCCompiler(CCompiler):
  41. compiler_type = 'unix'
  42. # These are used by CCompiler in two places: the constructor sets
  43. # instance attributes 'preprocessor', 'compiler', etc. from them, and
  44. # 'set_executable()' allows any of these to be set. The defaults here
  45. # are pretty generic; they will probably have to be set by an outsider
  46. # (eg. using information discovered by the sysconfig about building
  47. # Python extensions).
  48. executables = {'preprocessor' : None,
  49. 'compiler' : ["cc"],
  50. 'compiler_so' : ["cc"],
  51. 'compiler_cxx' : ["cc"],
  52. 'linker_so' : ["cc", "-shared"],
  53. 'linker_exe' : ["cc"],
  54. 'archiver' : ["ar", "-cr"],
  55. 'ranlib' : None,
  56. }
  57. if sys.platform[:6] == "darwin":
  58. executables['ranlib'] = ["ranlib"]
  59. # Needed for the filename generation methods provided by the base
  60. # class, CCompiler. NB. whoever instantiates/uses a particular
  61. # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
  62. # reasonable common default here, but it's not necessarily used on all
  63. # Unices!
  64. src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"]
  65. obj_extension = ".o"
  66. static_lib_extension = ".a"
  67. shared_lib_extension = ".so"
  68. dylib_lib_extension = ".dylib"
  69. xcode_stub_lib_extension = ".tbd"
  70. static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
  71. xcode_stub_lib_format = dylib_lib_format
  72. if sys.platform == "cygwin":
  73. exe_extension = ".exe"
  74. def preprocess(self, source,
  75. output_file=None, macros=None, include_dirs=None,
  76. extra_preargs=None, extra_postargs=None):
  77. ignore, macros, include_dirs = \
  78. self._fix_compile_args(None, macros, include_dirs)
  79. pp_opts = gen_preprocess_options(macros, include_dirs)
  80. pp_args = self.preprocessor + pp_opts
  81. if output_file:
  82. pp_args.extend(['-o', output_file])
  83. if extra_preargs:
  84. pp_args[:0] = extra_preargs
  85. if extra_postargs:
  86. pp_args.extend(extra_postargs)
  87. pp_args.append(source)
  88. # We need to preprocess: either we're being forced to, or we're
  89. # generating output to stdout, or there's a target output file and
  90. # the source file is newer than the target (or the target doesn't
  91. # exist).
  92. if self.force or output_file is None or newer(source, output_file):
  93. if output_file:
  94. self.mkpath(os.path.dirname(output_file))
  95. try:
  96. self.spawn(pp_args)
  97. except DistutilsExecError, msg:
  98. raise CompileError, msg
  99. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  100. compiler_so = self.compiler_so
  101. if sys.platform == 'darwin':
  102. compiler_so = _osx_support.compiler_fixup(compiler_so,
  103. cc_args + extra_postargs)
  104. try:
  105. self.spawn(compiler_so + cc_args + [src, '-o', obj] +
  106. extra_postargs)
  107. except DistutilsExecError, msg:
  108. raise CompileError, msg
  109. def create_static_lib(self, objects, output_libname,
  110. output_dir=None, debug=0, target_lang=None):
  111. objects, output_dir = self._fix_object_args(objects, output_dir)
  112. output_filename = \
  113. self.library_filename(output_libname, output_dir=output_dir)
  114. if self._need_link(objects, output_filename):
  115. self.mkpath(os.path.dirname(output_filename))
  116. self.spawn(self.archiver +
  117. [output_filename] +
  118. objects + self.objects)
  119. # Not many Unices required ranlib anymore -- SunOS 4.x is, I
  120. # think the only major Unix that does. Maybe we need some
  121. # platform intelligence here to skip ranlib if it's not
  122. # needed -- or maybe Python's configure script took care of
  123. # it for us, hence the check for leading colon.
  124. if self.ranlib:
  125. try:
  126. self.spawn(self.ranlib + [output_filename])
  127. except DistutilsExecError, msg:
  128. raise LibError, msg
  129. else:
  130. log.debug("skipping %s (up-to-date)", output_filename)
  131. def link(self, target_desc, objects,
  132. output_filename, output_dir=None, libraries=None,
  133. library_dirs=None, runtime_library_dirs=None,
  134. export_symbols=None, debug=0, extra_preargs=None,
  135. extra_postargs=None, build_temp=None, target_lang=None):
  136. objects, output_dir = self._fix_object_args(objects, output_dir)
  137. libraries, library_dirs, runtime_library_dirs = \
  138. self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
  139. lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
  140. libraries)
  141. if type(output_dir) not in (StringType, NoneType):
  142. raise TypeError, "'output_dir' must be a string or None"
  143. if output_dir is not None:
  144. output_filename = os.path.join(output_dir, output_filename)
  145. if self._need_link(objects, output_filename):
  146. ld_args = (objects + self.objects +
  147. lib_opts + ['-o', output_filename])
  148. if debug:
  149. ld_args[:0] = ['-g']
  150. if extra_preargs:
  151. ld_args[:0] = extra_preargs
  152. if extra_postargs:
  153. ld_args.extend(extra_postargs)
  154. self.mkpath(os.path.dirname(output_filename))
  155. try:
  156. if target_desc == CCompiler.EXECUTABLE:
  157. linker = self.linker_exe[:]
  158. else:
  159. linker = self.linker_so[:]
  160. if target_lang == "c++" and self.compiler_cxx:
  161. # skip over environment variable settings if /usr/bin/env
  162. # is used to set up the linker's environment.
  163. # This is needed on OSX. Note: this assumes that the
  164. # normal and C++ compiler have the same environment
  165. # settings.
  166. i = 0
  167. if os.path.basename(linker[0]) == "env":
  168. i = 1
  169. while '=' in linker[i]:
  170. i = i + 1
  171. linker[i] = self.compiler_cxx[i]
  172. if sys.platform == 'darwin':
  173. linker = _osx_support.compiler_fixup(linker, ld_args)
  174. self.spawn(linker + ld_args)
  175. except DistutilsExecError, msg:
  176. raise LinkError, msg
  177. else:
  178. log.debug("skipping %s (up-to-date)", output_filename)
  179. # -- Miscellaneous methods -----------------------------------------
  180. # These are all used by the 'gen_lib_options() function, in
  181. # ccompiler.py.
  182. def library_dir_option(self, dir):
  183. return "-L" + dir
  184. def _is_gcc(self, compiler_name):
  185. return "gcc" in compiler_name or "g++" in compiler_name
  186. def runtime_library_dir_option(self, dir):
  187. # XXX Hackish, at the very least. See Python bug #445902:
  188. # http://sourceforge.net/tracker/index.php
  189. # ?func=detail&aid=445902&group_id=5470&atid=105470
  190. # Linkers on different platforms need different options to
  191. # specify that directories need to be added to the list of
  192. # directories searched for dependencies when a dynamic library
  193. # is sought. GCC has to be told to pass the -R option through
  194. # to the linker, whereas other compilers just know this.
  195. # Other compilers may need something slightly different. At
  196. # this time, there's no way to determine this information from
  197. # the configuration data stored in the Python installation, so
  198. # we use this hack.
  199. compiler = os.path.basename(sysconfig.get_config_var("CC"))
  200. if sys.platform[:6] == "darwin":
  201. # MacOSX's linker doesn't understand the -R flag at all
  202. return "-L" + dir
  203. elif sys.platform[:5] == "hp-ux":
  204. if self._is_gcc(compiler):
  205. return ["-Wl,+s", "-L" + dir]
  206. return ["+s", "-L" + dir]
  207. elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5":
  208. return ["-rpath", dir]
  209. elif self._is_gcc(compiler):
  210. return "-Wl,-R" + dir
  211. else:
  212. return "-R" + dir
  213. def library_option(self, lib):
  214. return "-l" + lib
  215. def find_library_file(self, dirs, lib, debug=0):
  216. shared_f = self.library_filename(lib, lib_type='shared')
  217. dylib_f = self.library_filename(lib, lib_type='dylib')
  218. xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub')
  219. static_f = self.library_filename(lib, lib_type='static')
  220. if sys.platform == 'darwin':
  221. # On OSX users can specify an alternate SDK using
  222. # '-isysroot', calculate the SDK root if it is specified
  223. # (and use it further on)
  224. #
  225. # Note that, as of Xcode 7, Apple SDKs may contain textual stub
  226. # libraries with .tbd extensions rather than the normal .dylib
  227. # shared libraries installed in /. The Apple compiler tool
  228. # chain handles this transparently but it can cause problems
  229. # for programs that are being built with an SDK and searching
  230. # for specific libraries. Callers of find_library_file need to
  231. # keep in mind that the base filename of the returned SDK library
  232. # file might have a different extension from that of the library
  233. # file installed on the running system, for example:
  234. # /Applications/Xcode.app/Contents/Developer/Platforms/
  235. # MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
  236. # usr/lib/libedit.tbd
  237. # vs
  238. # /usr/lib/libedit.dylib
  239. cflags = sysconfig.get_config_var('CFLAGS')
  240. m = re.search(r'-isysroot\s+(\S+)', cflags)
  241. if m is None:
  242. sysroot = '/'
  243. else:
  244. sysroot = m.group(1)
  245. for dir in dirs:
  246. shared = os.path.join(dir, shared_f)
  247. dylib = os.path.join(dir, dylib_f)
  248. static = os.path.join(dir, static_f)
  249. xcode_stub = os.path.join(dir, xcode_stub_f)
  250. if sys.platform == 'darwin' and (
  251. dir.startswith('/System/') or (
  252. dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):
  253. shared = os.path.join(sysroot, dir[1:], shared_f)
  254. dylib = os.path.join(sysroot, dir[1:], dylib_f)
  255. static = os.path.join(sysroot, dir[1:], static_f)
  256. xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f)
  257. # We're second-guessing the linker here, with not much hard
  258. # data to go on: GCC seems to prefer the shared library, so I'm
  259. # assuming that *all* Unix C compilers do. And of course I'm
  260. # ignoring even GCC's "-static" option. So sue me.
  261. if os.path.exists(dylib):
  262. return dylib
  263. elif os.path.exists(xcode_stub):
  264. return xcode_stub
  265. elif os.path.exists(shared):
  266. return shared
  267. elif os.path.exists(static):
  268. return static
  269. # Oops, didn't find it in *any* of 'dirs'
  270. return None