gcc/g++ 如何支持c11 / c++11標准編譯


 如果用命令 g++ -g -Wall main.cpp  編譯以下代碼 :

/*
    file : main.cpp
*/
#include <stdio.h>

int main() {
	int a[5] = { 1, 2, 2, 5, 1 };
	for( int i:a ) {
		printf( "%d\n", a[i] );
	}
	return 0;
}

那么g++ 就會提示以下錯誤:

main.cpp: In function ‘int main()’:
main.cpp:5:13: error: range-based ‘for’ loops are not allowed in C++98 mode
  for( int i:a ) {

 

意思是指在C++98中不支持此循環方式,因為這是C++11新增的循環方式。

那么如果一定要編譯呢?

通過命令man g++可以得知以下方法:

g++ -g -Wall -std=c++11 main.cpp

除了g++ , gcc 也可以類似方法支持C11

gcc -g -Wall -std=c11 main.cpp

如果不想每次寫這個-std=C++11這個選項該怎么辦呢?

  方法出處:http://stackoverflow.com/questions/16886591/how-do-i-enable-c11-in-gcc

  方法1:寫Makefile

  方法2:取別名 :alias g++11="g++ -std=c++11"

 

Makefile 的話,像是:

all:
    g++ -g -std=c++11 main.cpp

其中 main.cpp 就是目標文件,運行 make 即可得到結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM