1

I'm handed a variable CC which contains the executable that refers to the compiler on the system. I need to take this executable and eventually call it with some compiler-specific link arguments.

My current approach seems very fragile:

def guess_compiler(cc):
    out = subprocess.check_output((cc, '--version'))
    for possible in (b'clang', b'gcc'):
        if possible in out:
            return possible.decode()
    else:
        # Fall back to gcc
        return 'gcc'

From this I'm using a mapping of the specific linker arguments I care about:

return {
    'clang': '-Wl,-undefined,dynamic_lookup',
    'gcc': '-Wl,--unresolved-symbols=ignore-all',
}[cc]

In short, I'm hoping there's a better (less fragile) way to do what I've accomplished.

For those looking for why I want something like this, it's mostly for portability in a project I'm implementing.

1 Answer 1

1

I'd rather call a compiler with some dummy code and these flags passed in. This is also what tools like Autotools and CMake do.

The problem with your current approach is that text string you see in --version output can actually be arbitrary. For instance, when clang wasn't that popular, FreeBSD's cc --version have been giving

GCC 4.2.1 -compatible Clang bla bla

So, just call the compiler with each flag you are interested in and then look at exit code.

An example of how to do this:

for flag in FLAGS:
    try:
        subprocess.check_call((cc, 'test.c', flag), cwd=tmpdir)
        return flag
    except subprocess.CalledProcessError:
        pass
else:
    # wellp, none of them worked, fall back to gcc and they'll get a
    # hopefully reasonable error message
    return FLAG_GCC
Sign up to request clarification or add additional context in comments.

1 Comment

Edited with what I attempted to go with :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.