0

I am trying to find the highest version of the C & C++ compiler installed on the OS.

I'm trying to optimize my code instead of taking up 25 lines and rewriting a bunch of if which commands over and over.

The script can be accessed by anyone on any version of distros and so the list can be long and full of possibilities and I want the latest version to run the build.

The reason I am posting this is because I keep getting back the match gcc-11 when gcc-12 is installed and shows up when manually running which gcc-12... so why is it only matching a lower version?

#!/bin/bash

clear

c_compilers=(gcc-13 gcc-12 gcc-11 gcc-10 gcc-9 gcc clang-16 clang-15 clang-14 clang-13 clang-12 clang-11 clang-10 clang)
cxx_compilers=(g++-13 g++-12 g++-11 g++-10 g++-9 g++ clang++-16 clang++-15 clang++-14 clang++-13 clang++-12 clang++-11 clang++-10 clang++)

for i in ${c_compilers[@]}
do
    cc_match="$(which $i)"
    if [ -n "$cc_match" ]; then
        CC="$cc_match"
        break
    fi
done

for i in ${cxx_compilers[@]}
do
    cxx_match="$(which $i)"
    if [ -n "$cxx_match" ]; then
        CXX="$cxx_match"
        break
    fi
done

echo $PATH
echo $CC
echo $CXX
slyfox1186
  • 301
  • 1
  • 13
  • 2
    Try putting `set -x` before this to get an execution trace as it runs, so you can see exactly where it's going wrong. Also, I don't think it's related, but there are a number of places where you really should double-quote variable references; [shellcheck.net](https://www.shellcheck.net) will point them out. – Gordon Davisson Jun 08 '23 at 03:34
  • 6
    there are builtin commands that are better than `which` -- https://stackoverflow.com/q/592620/7552 – glenn jackman Jun 08 '23 at 03:43
  • `for c in "${c_compilers[@]}"; do command -v "$c" &> /dev/null && { CC="$c"; break; }; done`? – Renaud Pacalet Jun 08 '23 at 09:49

1 Answers1

0

Since no one else had an answer I used the advice from the comments to come up with this.

#!/bin/bash
clear

# find the highest gcc version you have installed and set it as your CC compiler
type -P 'gcc' && export CC='gcc'
type -P 'gcc-9' && export CC='gcc-9'
type -P 'gcc-10' && export CC='gcc-10'
type -P 'gcc-11' && export CC='gcc-11'
type -P 'gcc-12' && export CC='gcc-12'
type -P 'gcc-13' && export CC='gcc-13'

# find the highest g++ version you have installed and set it as your CXX compiler
type -P 'g++' && export CXX='g++'
type -P 'g++-9' && export CXX='g++-9'
type -P 'g++-10' && export CXX='g++-10'
type -P 'g++-11' && export CXX='g++-11'
type -P 'g++-12' && export CXX='g++-12'
type -P 'g++-13' && export CXX='g++-13'

echo
echo $CC
echo
echo $CXX
slyfox1186
  • 301
  • 1
  • 13