1. 程式人生 > >關於編譯“bits/stdc++.h”標頭檔案

關於編譯“bits/stdc++.h”標頭檔案

首先講講“bits/stdc++.h”這個標頭檔案,一般都叫做萬能標頭檔案,比賽的時候用它基本上就不用寫其他的標頭檔案了,大部分的線上判題都支援。G++ 4.4以上就支援這個標頭檔案了

最近遇到的問題是在macos系統下,這段時間蘋果釋出了macOS High Sierra系統,剛好電腦硬碟空餘多,記憶體也比較大,我就用虛擬機器裝了一下,首次在終端中輸入g++命令,會提示安裝命令列開發者工具,照著提示安裝了,寫段測試程式碼測試一下

先建立原始碼檔案

vim 1.test

原始碼

#include "bits/stdc++.h"
using namespace std;
int main()
{
    cout
<< "Hello world!" << endl; return 0; }

儲存退出

ESC
:wq

再輸入

g++ -x c++ -o 1.out 1.test

發現報錯

muyangren907$ g++ -x c++ -o 1.out 1.test
1.test:1:10: fatal error: 'bits/stdc++.h' file not found
#include "bits/stdc++.h"
         ^~~~~~~~~~~~~~~
1 error generated.

錯誤原因是找不到’bits/stdc++.h’

為什麼會出現這種情況呢,我們不妨看看這裡所謂的g++

輸入

g++ -v

結果如下

muyangren907$ g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

顯然,這用的還是clang的編譯器,那如何使用正宗的GUN的GCC和G++呢
首先我們得安裝 homebrew,這可是個好東西,官網上的說明是

Homebrew
macOS 缺少的套件管理工具
[Homebrew官網](https://brew.sh/index_zh-cn.html)

安裝方法很簡單,在終端上輸入

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

即可,接下來就按操作安裝
另外提一句,貌似將DNS設定為8.8.8.8會加快下載速度,國內寬頻對Github的支援不是很好

安裝好homebrew之後,依次輸入如下指令

brew tap homebrew/versions
brew update
brew install gcc49

等待安裝完畢,輸入

g++-4.9 -v

檢視如下

muyangren907$ g++-4.9 -v
Using built-in specs.
COLLECT_GCC=g++-4.9
COLLECT_LTO_WRAPPER=/usr/local/Cellar/[email protected]4.9/4.9.4/libexec/gcc/x86_64-apple-darwin17.3.0/4.9.4/lto-wrapper
Target: x86_64-apple-darwin17.3.0
Configured with: ../configure --build=x86_64-apple-darwin17.3.0 --prefix=/usr/local/Cellar/[email protected]4.9/4.9.4 --libdir=/usr/local/Cellar/[email protected]4.9/4.9.4/lib/gcc/4.9 --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-4.9 --with-gmp=/usr/local/opt/[email protected]4 --with-mpfr=/usr/local/opt/[email protected]2 --with-mpc=/usr/local/opt/[email protected]0.8 --with-cloog=/usr/local/opt/cloog --with-isl=/usr/local/opt/[email protected]0.12 --with-system-zlib --enable-libstdcxx-time=yes --enable-stage1-checking --enable-checking=release --enable-lto --enable-plugin --with-build-config=bootstrap-debug --disable-werror --with-pkgversion='Homebrew GCC 4.9.4' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues MAKEINFO=missing --disable-nls --enable-multilib
Thread model: posix
gcc version 4.9.4 (Homebrew GCC 4.9.4) 

編譯剛才的原始碼可用如下命令

g++-4.9 -x c++ -o 1.out 1.test

成功編譯

另外,可能大多數人都使用xcode在macos上程式設計,但code blocks更為精簡,下面提一下關於如何讓codeblocks在macos上也能編譯“bits/stdc++.h”標頭檔案的問題

首先下載code blocks,官網上搜索下載即可,解壓後就是個單檔案

首次進入會有編譯器選擇介面,選第一個,進去主介面依次點選

Settings -> Compiler -> Global compiler settings -> Toolchain executables
Compiler installation directory

點右側方框,彈出資料夾選擇視窗,選擇帶有g++-4.9的bin資料夾的位置,我的位置

/usr/local

這裡寫圖片描述

下面的幾個空諸如

C compiler
C++ compiler
Linker for dynamic libs

如圖設定即可
最後點選OK