Jason Mock
Jason Mock

Reputation: 823

Distutils - How to disable including debug symbols when building an extension

I've written a boost-python extension that currently is being built via distutils.

Unfortunately I have been unable to find a way, within distutils, to build the extension without debug symbols or have the symbols stripped from the extension upon installation.
Note: I am not passing --debug or -g to build command of distutils (e.g., python setup.py build), and my compiler is gcc on Linux.

Exampled setup.py:

from distutils.core import setup
from distutils.extension import Extension

setup(name="myPy",
      ext_modules = [
         Extension("MyPyExt", ["MyPyExt.cpp"],
                   libraries = ["boost_python"])
      ])

Upvotes: 8

Views: 5717

Answers (3)

Tora
Tora

Reputation: 1020

@hithwen's solution works well with python3.5, installed by MacPorts, running on MacOS 10.13.4.

However, platform.system() returns 'Darwin', not 'Linux' in my case.
On Ubuntu 16.04, -g seems to appear at the beginning or at the end. So a little bit tweaked:

import sys
import re
from distutils import sysconfig
from distutils.core import setup, Extension

if sys.platform == 'linux' or sys.platform == 'darwin':
  sysconfig.get_config_var(None)  # to fill up _config_vars
  d = sysconfig._config_vars
  for x in ['OPT', 'CFLAGS', 'PY_CFLAGS', 'PY_CORE_CFLAGS', 'CONFIGURE_CFLAGS', 'LDSHARED']:
    d[x] = re.sub(' -g ', ' ', d[x])
    d[x] = re.sub('^-g ', '',  d[x])
    d[x] = re.sub(' -g$', '',  d[x])

setup(...)

Thank you @hithwen!

Upvotes: 0

Wrzlprmft
Wrzlprmft

Reputation: 4434

You can use the option extra_compile_args to pass arguments to the compiler which are appended last and thus have highest priority. Thus, if you include -g0 (no debug symbols) in extra_compile_args, this overrides the -g set by Distutils/Setuptools. In your example:

from distutils.core import setup
from distutils.extension import Extension

setup(
    name="myPy",
    ext_modules = [Extension(
        "MyPyExt",
        ["MyPyExt.cpp"],
        libraries = ["boost_python"],
        extra_compile_args = ["-g0"]
        )]
    )

See also: How may I override the compiler (gcc) flags that setup.py uses by default?

Upvotes: 10

hithwen
hithwen

Reputation: 2203

I've found a way but is a bit hacky:

from distutils import sysconfig
from distutils.core import setup
import platform


if platform.system() != 'Windows':  # When compilinig con visual no -g is added to params
    cflags = sysconfig.get_config_var('CFLAGS')
    opt = sysconfig.get_config_var('OPT')
    sysconfig._config_vars['CFLAGS'] = cflags.replace(' -g ', ' ')
    sysconfig._config_vars['OPT'] = opt.replace(' -g ', ' ')

if platform.system() == 'Linux':  # In macos there seems not to be -g in LDSHARED
    ldshared = sysconfig.get_config_var('LDSHARED')
    sysconfig._config_vars['LDSHARED'] = ldshared.replace(' -g ', ' ')

setup(...)

Upvotes: 5

Related Questions