[c++/gcc] Centos 7.9升級 gcc 4.8.5 到 gcc11 [轉]

千千寰宇發表於2024-03-22

0 序

  • 本文背景:因在centos 7.9 server上安裝nodejs21.7.1,編譯nodejs時,依賴了gnu17/gcc11。

例如:遇到 Qt requires c++11 support-std=gnu++17
例如:編譯器不支援c++17,就會提示:g++: error: unrecognized command line option ‘-std=c++17’
例如:編譯器不支援c++17,就會提示:g++: error: unrecognized command line option ‘-std=gnu++17’

  • 然而,centos 7.9 預設的 gcc版本為 4.8.5。因此,需要升級到 gcc11。這種升級場景,在centos7.9中因為nodejs等重要元件,而變得較為頻繁、且重要。故記錄之。
  • 環境資訊
  • centos : 7.9.2009
  • gcc 原版本 : 4.8.5
  • 目標升級版本 : 11

1 基於centos7.9 安裝 gcc 4.8.5(預設版本)

  • 安裝
yum -y update gcc
yum -y install gcc+ gcc-c++
  • 檢視版本
# g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

2 升級步驟 : gcc 4.8.5 -> gcc 11

2.1 升級

  • 安裝centos-release-scl

如果出現許可權問題使用超級使用者(sudo)或者root進行安裝

yum -y install centos-release-scl

安裝devtoolset,如果想安裝其他版本,例如 gcc7.* 改為 devtoolset-7-gcc* 即可

yum -y install devtoolset-11-gcc*

注:啟用gcc11,devtoolset會安裝在/opt/rh目錄下

cd /opt/rh/devtoolset-11/ 
  • 每個版本下面都會有個enable檔案,執行以下命令即可啟用
source ./enable

如果想要切換到不同的版本時,只要執行命令即可

source /opt/rh/devtoolset-11/enable 
  • 直接替換相應軟連線

該方法可以避免每次都要進行enable

mv /usr/bin/gcc /usr/bin/gcc.bak

ln -s /opt/rh/devtoolset-11/root/bin/gcc /usr/bin/gcc

mv /usr/bin/g++ /usr/bin/g++.bak

ln -s /opt/rh/devtoolset-11/root/bin/g++ /usr/bin/g++

mv /usr/bin/c++ /usr/bin/c++.bak

ln -s /opt/rh/devtoolset-11/root/bin/c++ /usr/bin/c++

mv /usr/bin/cpp /usr/bin/cpp.bak

ln -s /opt/rh/devtoolset-11/root/bin/cpp /usr/bin/cpp

mv /usr/bin/cc /usr/bin/cc.bak

ln -s /opt/rh/devtoolset-11/root/bin/cc /usr/bin/cc

2.2 查驗:檢視版本

# g++ --version
g++ (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9)
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# gcc --version
gcc (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9)
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

uploading-image-28412.png

X 參考文獻

  • Centos7.9 gcc4.8.5升級到gcc11 - 部落格園 【推薦】
  • CentOS下g++: command not found問題的解決 - CSDN
  • [微控制器框架][esp32] 使用C++17新特性報錯 - CSDN

相關文章