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 即可得到结果

 

posted @ 2015-04-11 23:38  Emerald  阅读(35587)  评论(3编辑  收藏  举报