/Lib/distutils/msvc9compiler.py

http://unladen-swallow.googlecode.com/ · Python · 708 lines · 493 code · 86 blank · 129 comment · 130 complexity · 9888b9375bbd2befc9963cfa201512a3 MD5 · raw file

  1. """distutils.msvc9compiler
  2. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  3. for the Microsoft Visual Studio 2008.
  4. The module is compatible with VS 2005 and VS 2008. You can find legacy support
  5. for older versions of VS in distutils.msvccompiler.
  6. """
  7. # Written by Perry Stoll
  8. # hacked by Robin Becker and Thomas Heller to do a better job of
  9. # finding DevStudio (through the registry)
  10. # ported to VS2005 and VS 2008 by Christian Heimes
  11. __revision__ = "$Id: msvc9compiler.py 68082 2008-12-30 23:06:46Z tarek.ziade $"
  12. import os
  13. import subprocess
  14. import sys
  15. from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
  16. CompileError, LibError, LinkError)
  17. from distutils.ccompiler import (CCompiler, gen_preprocess_options,
  18. gen_lib_options)
  19. from distutils import log
  20. from distutils.util import get_platform
  21. import _winreg
  22. RegOpenKeyEx = _winreg.OpenKeyEx
  23. RegEnumKey = _winreg.EnumKey
  24. RegEnumValue = _winreg.EnumValue
  25. RegError = _winreg.error
  26. HKEYS = (_winreg.HKEY_USERS,
  27. _winreg.HKEY_CURRENT_USER,
  28. _winreg.HKEY_LOCAL_MACHINE,
  29. _winreg.HKEY_CLASSES_ROOT)
  30. VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
  31. WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
  32. NET_BASE = r"Software\Microsoft\.NETFramework"
  33. # A map keyed by get_platform() return values to values accepted by
  34. # 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is
  35. # the param to cross-compile on x86 targetting amd64.)
  36. PLAT_TO_VCVARS = {
  37. 'win32' : 'x86',
  38. 'win-amd64' : 'amd64',
  39. 'win-ia64' : 'ia64',
  40. }
  41. class Reg:
  42. """Helper class to read values from the registry
  43. """
  44. @classmethod
  45. def get_value(cls, path, key):
  46. for base in HKEYS:
  47. d = cls.read_values(base, path)
  48. if d and key in d:
  49. return d[key]
  50. raise KeyError(key)
  51. @classmethod
  52. def read_keys(cls, base, key):
  53. """Return list of registry keys."""
  54. try:
  55. handle = RegOpenKeyEx(base, key)
  56. except RegError:
  57. return None
  58. L = []
  59. i = 0
  60. while True:
  61. try:
  62. k = RegEnumKey(handle, i)
  63. except RegError:
  64. break
  65. L.append(k)
  66. i += 1
  67. return L
  68. @classmethod
  69. def read_values(cls, base, key):
  70. """Return dict of registry keys and values.
  71. All names are converted to lowercase.
  72. """
  73. try:
  74. handle = RegOpenKeyEx(base, key)
  75. except RegError:
  76. return None
  77. d = {}
  78. i = 0
  79. while True:
  80. try:
  81. name, value, type = RegEnumValue(handle, i)
  82. except RegError:
  83. break
  84. name = name.lower()
  85. d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
  86. i += 1
  87. return d
  88. @staticmethod
  89. def convert_mbcs(s):
  90. dec = getattr(s, "decode", None)
  91. if dec is not None:
  92. try:
  93. s = dec("mbcs")
  94. except UnicodeError:
  95. pass
  96. return s
  97. class MacroExpander:
  98. def __init__(self, version):
  99. self.macros = {}
  100. self.vsbase = VS_BASE % version
  101. self.load_macros(version)
  102. def set_macro(self, macro, path, key):
  103. self.macros["$(%s)" % macro] = Reg.get_value(path, key)
  104. def load_macros(self, version):
  105. self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir")
  106. self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir")
  107. self.set_macro("FrameworkDir", NET_BASE, "installroot")
  108. try:
  109. if version >= 8.0:
  110. self.set_macro("FrameworkSDKDir", NET_BASE,
  111. "sdkinstallrootv2.0")
  112. else:
  113. raise KeyError("sdkinstallrootv2.0")
  114. except KeyError as exc: #
  115. raise DistutilsPlatformError(
  116. """Python was built with Visual Studio 2008;
  117. extensions must be built with a compiler than can generate compatible binaries.
  118. Visual Studio 2008 was not found on this system. If you have Cygwin installed,
  119. you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
  120. if version >= 9.0:
  121. self.set_macro("FrameworkVersion", self.vsbase, "clr version")
  122. self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder")
  123. else:
  124. p = r"Software\Microsoft\NET Framework Setup\Product"
  125. for base in HKEYS:
  126. try:
  127. h = RegOpenKeyEx(base, p)
  128. except RegError:
  129. continue
  130. key = RegEnumKey(h, 0)
  131. d = Reg.get_value(base, r"%s\%s" % (p, key))
  132. self.macros["$(FrameworkVersion)"] = d["version"]
  133. def sub(self, s):
  134. for k, v in self.macros.items():
  135. s = s.replace(k, v)
  136. return s
  137. def get_build_version():
  138. """Return the version of MSVC that was used to build Python.
  139. For Python 2.3 and up, the version number is included in
  140. sys.version. For earlier versions, assume the compiler is MSVC 6.
  141. """
  142. prefix = "MSC v."
  143. i = sys.version.find(prefix)
  144. if i == -1:
  145. return 6
  146. i = i + len(prefix)
  147. s, rest = sys.version[i:].split(" ", 1)
  148. majorVersion = int(s[:-2]) - 6
  149. minorVersion = int(s[2:3]) / 10.0
  150. # I don't think paths are affected by minor version in version 6
  151. if majorVersion == 6:
  152. minorVersion = 0
  153. if majorVersion >= 6:
  154. return majorVersion + minorVersion
  155. # else we don't know what version of the compiler this is
  156. return None
  157. def normalize_and_reduce_paths(paths):
  158. """Return a list of normalized paths with duplicates removed.
  159. The current order of paths is maintained.
  160. """
  161. # Paths are normalized so things like: /a and /a/ aren't both preserved.
  162. reduced_paths = []
  163. for p in paths:
  164. np = os.path.normpath(p)
  165. # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
  166. if np not in reduced_paths:
  167. reduced_paths.append(np)
  168. return reduced_paths
  169. def removeDuplicates(variable):
  170. """Remove duplicate values of an environment variable.
  171. """
  172. oldList = variable.split(os.pathsep)
  173. newList = []
  174. for i in oldList:
  175. if i not in newList:
  176. newList.append(i)
  177. newVariable = os.pathsep.join(newList)
  178. return newVariable
  179. def find_vcvarsall(version):
  180. """Find the vcvarsall.bat file
  181. At first it tries to find the productdir of VS 2008 in the registry. If
  182. that fails it falls back to the VS90COMNTOOLS env var.
  183. """
  184. vsbase = VS_BASE % version
  185. try:
  186. productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
  187. "productdir")
  188. except KeyError:
  189. log.debug("Unable to find productdir in registry")
  190. productdir = None
  191. if not productdir or not os.path.isdir(productdir):
  192. toolskey = "VS%0.f0COMNTOOLS" % version
  193. toolsdir = os.environ.get(toolskey, None)
  194. if toolsdir and os.path.isdir(toolsdir):
  195. productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
  196. productdir = os.path.abspath(productdir)
  197. if not os.path.isdir(productdir):
  198. log.debug("%s is not a valid directory" % productdir)
  199. return None
  200. else:
  201. log.debug("Env var %s is not set or invalid" % toolskey)
  202. if not productdir:
  203. log.debug("No productdir found")
  204. return None
  205. vcvarsall = os.path.join(productdir, "vcvarsall.bat")
  206. if os.path.isfile(vcvarsall):
  207. return vcvarsall
  208. log.debug("Unable to find vcvarsall.bat")
  209. return None
  210. def query_vcvarsall(version, arch="x86"):
  211. """Launch vcvarsall.bat and read the settings from its environment
  212. """
  213. vcvarsall = find_vcvarsall(version)
  214. interesting = set(("include", "lib", "libpath", "path"))
  215. result = {}
  216. if vcvarsall is None:
  217. raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  218. log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
  219. popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
  220. stdout=subprocess.PIPE,
  221. stderr=subprocess.PIPE)
  222. stdout, stderr = popen.communicate()
  223. if popen.wait() != 0:
  224. raise DistutilsPlatformError(stderr.decode("mbcs"))
  225. stdout = stdout.decode("mbcs")
  226. for line in stdout.split("\n"):
  227. line = Reg.convert_mbcs(line)
  228. if '=' not in line:
  229. continue
  230. line = line.strip()
  231. key, value = line.split('=', 1)
  232. key = key.lower()
  233. if key in interesting:
  234. if value.endswith(os.pathsep):
  235. value = value[:-1]
  236. result[key] = removeDuplicates(value)
  237. if len(result) != len(interesting):
  238. raise ValueError(str(list(result.keys())))
  239. return result
  240. # More globals
  241. VERSION = get_build_version()
  242. if VERSION < 8.0:
  243. raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION)
  244. # MACROS = MacroExpander(VERSION)
  245. class MSVCCompiler(CCompiler) :
  246. """Concrete class that implements an interface to Microsoft Visual C++,
  247. as defined by the CCompiler abstract class."""
  248. compiler_type = 'msvc'
  249. # Just set this so CCompiler's constructor doesn't barf. We currently
  250. # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  251. # as it really isn't necessary for this sort of single-compiler class.
  252. # Would be nice to have a consistent interface with UnixCCompiler,
  253. # though, so it's worth thinking about.
  254. executables = {}
  255. # Private class data (need to distinguish C from C++ source for compiler)
  256. _c_extensions = ['.c']
  257. _cpp_extensions = ['.cc', '.cpp', '.cxx']
  258. _rc_extensions = ['.rc']
  259. _mc_extensions = ['.mc']
  260. # Needed for the filename generation methods provided by the
  261. # base class, CCompiler.
  262. src_extensions = (_c_extensions + _cpp_extensions +
  263. _rc_extensions + _mc_extensions)
  264. res_extension = '.res'
  265. obj_extension = '.obj'
  266. static_lib_extension = '.lib'
  267. shared_lib_extension = '.dll'
  268. static_lib_format = shared_lib_format = '%s%s'
  269. exe_extension = '.exe'
  270. def __init__(self, verbose=0, dry_run=0, force=0):
  271. CCompiler.__init__ (self, verbose, dry_run, force)
  272. self.__version = VERSION
  273. self.__root = r"Software\Microsoft\VisualStudio"
  274. # self.__macros = MACROS
  275. self.__paths = []
  276. # target platform (.plat_name is consistent with 'bdist')
  277. self.plat_name = None
  278. self.__arch = None # deprecated name
  279. self.initialized = False
  280. def initialize(self, plat_name=None):
  281. # multi-init means we would need to check platform same each time...
  282. assert not self.initialized, "don't init multiple times"
  283. if plat_name is None:
  284. plat_name = get_platform()
  285. # sanity check for platforms to prevent obscure errors later.
  286. ok_plats = 'win32', 'win-amd64', 'win-ia64'
  287. if plat_name not in ok_plats:
  288. raise DistutilsPlatformError("--plat-name must be one of %s" %
  289. (ok_plats,))
  290. if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
  291. # Assume that the SDK set up everything alright; don't try to be
  292. # smarter
  293. self.cc = "cl.exe"
  294. self.linker = "link.exe"
  295. self.lib = "lib.exe"
  296. self.rc = "rc.exe"
  297. self.mc = "mc.exe"
  298. else:
  299. # On x86, 'vcvars32.bat amd64' creates an env that doesn't work;
  300. # to cross compile, you use 'x86_amd64'.
  301. # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross
  302. # compile use 'x86' (ie, it runs the x86 compiler directly)
  303. # No idea how itanium handles this, if at all.
  304. if plat_name == get_platform() or plat_name == 'win32':
  305. # native build or cross-compile to win32
  306. plat_spec = PLAT_TO_VCVARS[plat_name]
  307. else:
  308. # cross compile from win32 -> some 64bit
  309. plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \
  310. PLAT_TO_VCVARS[plat_name]
  311. vc_env = query_vcvarsall(VERSION, plat_spec)
  312. # take care to only use strings in the environment.
  313. self.__paths = vc_env['path'].encode('mbcs').split(os.pathsep)
  314. os.environ['lib'] = vc_env['lib'].encode('mbcs')
  315. os.environ['include'] = vc_env['include'].encode('mbcs')
  316. if len(self.__paths) == 0:
  317. raise DistutilsPlatformError("Python was built with %s, "
  318. "and extensions need to be built with the same "
  319. "version of the compiler, but it isn't installed."
  320. % self.__product)
  321. self.cc = self.find_exe("cl.exe")
  322. self.linker = self.find_exe("link.exe")
  323. self.lib = self.find_exe("lib.exe")
  324. self.rc = self.find_exe("rc.exe") # resource compiler
  325. self.mc = self.find_exe("mc.exe") # message compiler
  326. #self.set_path_env_var('lib')
  327. #self.set_path_env_var('include')
  328. # extend the MSVC path with the current path
  329. try:
  330. for p in os.environ['path'].split(';'):
  331. self.__paths.append(p)
  332. except KeyError:
  333. pass
  334. self.__paths = normalize_and_reduce_paths(self.__paths)
  335. os.environ['path'] = ";".join(self.__paths)
  336. self.preprocess_options = None
  337. if self.__arch == "x86":
  338. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3',
  339. '/DNDEBUG']
  340. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3',
  341. '/Z7', '/D_DEBUG']
  342. else:
  343. # Win64
  344. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' ,
  345. '/DNDEBUG']
  346. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
  347. '/Z7', '/D_DEBUG']
  348. self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  349. if self.__version >= 7:
  350. self.ldflags_shared_debug = [
  351. '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG', '/pdb:None'
  352. ]
  353. self.ldflags_static = [ '/nologo']
  354. self.initialized = True
  355. # -- Worker methods ------------------------------------------------
  356. def object_filenames(self,
  357. source_filenames,
  358. strip_dir=0,
  359. output_dir=''):
  360. # Copied from ccompiler.py, extended to return .res as 'object'-file
  361. # for .rc input file
  362. if output_dir is None: output_dir = ''
  363. obj_names = []
  364. for src_name in source_filenames:
  365. (base, ext) = os.path.splitext (src_name)
  366. base = os.path.splitdrive(base)[1] # Chop off the drive
  367. base = base[os.path.isabs(base):] # If abs, chop off leading /
  368. if ext not in self.src_extensions:
  369. # Better to raise an exception instead of silently continuing
  370. # and later complain about sources and targets having
  371. # different lengths
  372. raise CompileError ("Don't know how to compile %s" % src_name)
  373. if strip_dir:
  374. base = os.path.basename (base)
  375. if ext in self._rc_extensions:
  376. obj_names.append (os.path.join (output_dir,
  377. base + self.res_extension))
  378. elif ext in self._mc_extensions:
  379. obj_names.append (os.path.join (output_dir,
  380. base + self.res_extension))
  381. else:
  382. obj_names.append (os.path.join (output_dir,
  383. base + self.obj_extension))
  384. return obj_names
  385. def compile(self, sources,
  386. output_dir=None, macros=None, include_dirs=None, debug=0,
  387. extra_preargs=None, extra_postargs=None, depends=None):
  388. if not self.initialized:
  389. self.initialize()
  390. compile_info = self._setup_compile(output_dir, macros, include_dirs,
  391. sources, depends, extra_postargs)
  392. macros, objects, extra_postargs, pp_opts, build = compile_info
  393. compile_opts = extra_preargs or []
  394. compile_opts.append ('/c')
  395. if debug:
  396. compile_opts.extend(self.compile_options_debug)
  397. else:
  398. compile_opts.extend(self.compile_options)
  399. for obj in objects:
  400. try:
  401. src, ext = build[obj]
  402. except KeyError:
  403. continue
  404. if debug:
  405. # pass the full pathname to MSVC in debug mode,
  406. # this allows the debugger to find the source file
  407. # without asking the user to browse for it
  408. src = os.path.abspath(src)
  409. if ext in self._c_extensions:
  410. input_opt = "/Tc" + src
  411. elif ext in self._cpp_extensions:
  412. input_opt = "/Tp" + src
  413. elif ext in self._rc_extensions:
  414. # compile .RC to .RES file
  415. input_opt = src
  416. output_opt = "/fo" + obj
  417. try:
  418. self.spawn([self.rc] + pp_opts +
  419. [output_opt] + [input_opt])
  420. except DistutilsExecError as msg:
  421. raise CompileError(msg)
  422. continue
  423. elif ext in self._mc_extensions:
  424. # Compile .MC to .RC file to .RES file.
  425. # * '-h dir' specifies the directory for the
  426. # generated include file
  427. # * '-r dir' specifies the target directory of the
  428. # generated RC file and the binary message resource
  429. # it includes
  430. #
  431. # For now (since there are no options to change this),
  432. # we use the source-directory for the include file and
  433. # the build directory for the RC file and message
  434. # resources. This works at least for win32all.
  435. h_dir = os.path.dirname(src)
  436. rc_dir = os.path.dirname(obj)
  437. try:
  438. # first compile .MC to .RC and .H file
  439. self.spawn([self.mc] +
  440. ['-h', h_dir, '-r', rc_dir] + [src])
  441. base, _ = os.path.splitext (os.path.basename (src))
  442. rc_file = os.path.join (rc_dir, base + '.rc')
  443. # then compile .RC to .RES file
  444. self.spawn([self.rc] +
  445. ["/fo" + obj] + [rc_file])
  446. except DistutilsExecError as msg:
  447. raise CompileError(msg)
  448. continue
  449. else:
  450. # how to handle this file?
  451. raise CompileError("Don't know how to compile %s to %s"
  452. % (src, obj))
  453. output_opt = "/Fo" + obj
  454. try:
  455. self.spawn([self.cc] + compile_opts + pp_opts +
  456. [input_opt, output_opt] +
  457. extra_postargs)
  458. except DistutilsExecError as msg:
  459. raise CompileError(msg)
  460. return objects
  461. def create_static_lib(self,
  462. objects,
  463. output_libname,
  464. output_dir=None,
  465. debug=0,
  466. target_lang=None):
  467. if not self.initialized:
  468. self.initialize()
  469. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  470. output_filename = self.library_filename(output_libname,
  471. output_dir=output_dir)
  472. if self._need_link(objects, output_filename):
  473. lib_args = objects + ['/OUT:' + output_filename]
  474. if debug:
  475. pass # XXX what goes here?
  476. try:
  477. self.spawn([self.lib] + lib_args)
  478. except DistutilsExecError as msg:
  479. raise LibError(msg)
  480. else:
  481. log.debug("skipping %s (up-to-date)", output_filename)
  482. def link(self,
  483. target_desc,
  484. objects,
  485. output_filename,
  486. output_dir=None,
  487. libraries=None,
  488. library_dirs=None,
  489. runtime_library_dirs=None,
  490. export_symbols=None,
  491. debug=0,
  492. extra_preargs=None,
  493. extra_postargs=None,
  494. build_temp=None,
  495. target_lang=None):
  496. if not self.initialized:
  497. self.initialize()
  498. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  499. fixed_args = self._fix_lib_args(libraries, library_dirs,
  500. runtime_library_dirs)
  501. (libraries, library_dirs, runtime_library_dirs) = fixed_args
  502. if runtime_library_dirs:
  503. self.warn ("I don't know what to do with 'runtime_library_dirs': "
  504. + str (runtime_library_dirs))
  505. lib_opts = gen_lib_options(self,
  506. library_dirs, runtime_library_dirs,
  507. libraries)
  508. if output_dir is not None:
  509. output_filename = os.path.join(output_dir, output_filename)
  510. if self._need_link(objects, output_filename):
  511. if target_desc == CCompiler.EXECUTABLE:
  512. if debug:
  513. ldflags = self.ldflags_shared_debug[1:]
  514. else:
  515. ldflags = self.ldflags_shared[1:]
  516. else:
  517. if debug:
  518. ldflags = self.ldflags_shared_debug
  519. else:
  520. ldflags = self.ldflags_shared
  521. export_opts = []
  522. for sym in (export_symbols or []):
  523. export_opts.append("/EXPORT:" + sym)
  524. ld_args = (ldflags + lib_opts + export_opts +
  525. objects + ['/OUT:' + output_filename])
  526. # The MSVC linker generates .lib and .exp files, which cannot be
  527. # suppressed by any linker switches. The .lib files may even be
  528. # needed! Make sure they are generated in the temporary build
  529. # directory. Since they have different names for debug and release
  530. # builds, they can go into the same directory.
  531. build_temp = os.path.dirname(objects[0])
  532. if export_symbols is not None:
  533. (dll_name, dll_ext) = os.path.splitext(
  534. os.path.basename(output_filename))
  535. implib_file = os.path.join(
  536. build_temp,
  537. self.library_filename(dll_name))
  538. ld_args.append ('/IMPLIB:' + implib_file)
  539. # Embedded manifests are recommended - see MSDN article titled
  540. # "How to: Embed a Manifest Inside a C/C++ Application"
  541. # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
  542. # Ask the linker to generate the manifest in the temp dir, so
  543. # we can embed it later.
  544. temp_manifest = os.path.join(
  545. build_temp,
  546. os.path.basename(output_filename) + ".manifest")
  547. ld_args.append('/MANIFESTFILE:' + temp_manifest)
  548. if extra_preargs:
  549. ld_args[:0] = extra_preargs
  550. if extra_postargs:
  551. ld_args.extend(extra_postargs)
  552. self.mkpath(os.path.dirname(output_filename))
  553. try:
  554. self.spawn([self.linker] + ld_args)
  555. except DistutilsExecError as msg:
  556. raise LinkError(msg)
  557. # embed the manifest
  558. # XXX - this is somewhat fragile - if mt.exe fails, distutils
  559. # will still consider the DLL up-to-date, but it will not have a
  560. # manifest. Maybe we should link to a temp file? OTOH, that
  561. # implies a build environment error that shouldn't go undetected.
  562. mfid = 1 if target_desc == CCompiler.EXECUTABLE else 2
  563. out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
  564. try:
  565. self.spawn(['mt.exe', '-nologo', '-manifest',
  566. temp_manifest, out_arg])
  567. except DistutilsExecError as msg:
  568. raise LinkError(msg)
  569. else:
  570. log.debug("skipping %s (up-to-date)", output_filename)
  571. # -- Miscellaneous methods -----------------------------------------
  572. # These are all used by the 'gen_lib_options() function, in
  573. # ccompiler.py.
  574. def library_dir_option(self, dir):
  575. return "/LIBPATH:" + dir
  576. def runtime_library_dir_option(self, dir):
  577. raise DistutilsPlatformError(
  578. "don't know how to set runtime library search path for MSVC++")
  579. def library_option(self, lib):
  580. return self.library_filename(lib)
  581. def find_library_file(self, dirs, lib, debug=0):
  582. # Prefer a debugging library if found (and requested), but deal
  583. # with it if we don't have one.
  584. if debug:
  585. try_names = [lib + "_d", lib]
  586. else:
  587. try_names = [lib]
  588. for dir in dirs:
  589. for name in try_names:
  590. libfile = os.path.join(dir, self.library_filename (name))
  591. if os.path.exists(libfile):
  592. return libfile
  593. else:
  594. # Oops, didn't find it in *any* of 'dirs'
  595. return None
  596. # Helper methods for using the MSVC registry settings
  597. def find_exe(self, exe):
  598. """Return path to an MSVC executable program.
  599. Tries to find the program in several places: first, one of the
  600. MSVC program search paths from the registry; next, the directories
  601. in the PATH environment variable. If any of those work, return an
  602. absolute path that is known to exist. If none of them work, just
  603. return the original program name, 'exe'.
  604. """
  605. for p in self.__paths:
  606. fn = os.path.join(os.path.abspath(p), exe)
  607. if os.path.isfile(fn):
  608. return fn
  609. # didn't find it; try existing path
  610. for p in os.environ['Path'].split(';'):
  611. fn = os.path.join(os.path.abspath(p),exe)
  612. if os.path.isfile(fn):
  613. return fn
  614. return exe