Raspberry Pi 安裝 GCC 及 C++

Linux作業系統安裝、設定與管理 (CentOS、Ubuntu)
回覆文章
inho
文章: 42
註冊時間: 2017-12-08, 23:00

Raspberry Pi 安裝 GCC 及 C++

文章 inho » 2018-01-28, 07:38

一、先取得 GCC 7 的 Binary 程式:
$ cd ~
$ git clone https://bitbucket.org/sol_prog/raspberr ... binary.git
// 解開 壓縮檔
$ cd raspberry-pi-gcc-binary
$ tar xf gcc-7.2.0.tar.bz2
$ sudo mv gcc-7.2.0 /usr/local
// 接下來 設定 執行時的工作環境 (環境變數 Path) ,此為暫時性的設定,下次再登入時必須重設一次
$ export PATH=/usr/local/gcc-7.2.0/bin:$PATH

// 以下指令將設定環境變數寫入登入時會自動執行的 batch file: .bashrc (針對 bash shell 的使用者)
$ echo 'export PATH=/usr/local/gcc-7.2.0/bin:$PATH' >> .bashrc
$ source .bashrc

// 完成後,Check 一下 GCC版本
$ gcc-7.2.0 --version
1 pi@raspberrypi:~ $ gcc-7.2.0 --version
2 gcc-7.2.0 (GCC) 7.2.0
3 Copyright (C) 2017 Free Software Foundation, Inc.
4 This is free software; see the source for copying conditions. There is NO
5 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
6
7 pi@raspberrypi:~ $
// 完成安裝後,移除不再需要的檔案
$ cd ~
$ rm -r raspberry-pi-gcc-binary

The above procedure will keep GCC 6.3 as the default C and C++ compiler for any package that depends on it. If you want to compile C programs you could use gcc-7.2.0, for C++ g++-7.2.0 and for Fortran gfortran-7.2.0.

Let’s try to compile and run a C++17 code that uses an if block with init-statement (the example is a bit silly, but it will show you how to compile C++17 programs):

現在測試以下程式:
#include <iostream>
using namespace std ;
int main( )
{
if (int a = 5; a < 8) {
cout << "Local variable a is < 8\n";
} else
{
cout << "Local variable a is >= 8\n";
}
return 0;
}

Save the above code in a file named if_test.cpp and compile it with:

1 g++-7.2.0 -std=c++17 -Wall -pedantic if_test.cpp -o if_test
This is what I see on my Pi:

1 pi@raspberrypi:~ $ g++-7.2.0 -std=c++17 -Wall -pedantic if_test.cpp -o if_test
2 pi@raspberrypi:~ $ ./if_test
3 Local variable a is < 8
4 pi@raspberrypi:~ $

回覆文章