如何修改clang++编译时默认的C++版本?
问题描述
编写了一段滑动谜题的C代码,编译时出现连续右尖括号(>>)需加空格的错误。经确认,clang默认使用C03标准(通过命令clang++ -E -x c++ - -dM < /dev/null | grep __cplusplus验证,__cplusplus值为199711L),而该版本不支持连续右尖括号的写法。请问如何修改clang编译时的默认C++版本?
代码示例
#include <iostream> #include <queue> #include <unordered_set> using namespace std; string swap(string s, int i, int j) { char temp = s[i]; s[i] = s[j]; s[j] = temp; return s; } int slidingPuzzle(vector<vector<int>>& board) { int rows = 2; int cols = 3; string target = "1234560"; string start = ""; for (int i = 0; i < rows; i++) { for (int j = 0; i < cols; j++) { start = start + to_string(board[i][j]); } } vector<vector<int>> neighbour = { {1, 3}, {0, 4, 2}, {1, 5}, {0, 4}, {3, 1, 5}, {4, 2}, }; queue<string> q; unordered_set<string> visited; q.push(start); visited.insert(start); int step = 0; while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { string cur = q.front(); if (target == cur) { return step; } int idx = 0; for (; cur[idx] != '0'; idx++) ; for (int adj : neighbour[idx]) { string new_board = swap(cur, adj, idx); if (!visited.count(new_board)) { q.push(new_board); visited.insert(new_board); } } } step++; } return -1; } int main() { vector<vector<int>> board = { {1, 2, 3}, {4, 0, 5}, }; int a = slidingPuzzle(board); cout << a << endl; }
编译错误信息
main.cpp:11:36: error: a space is required between consecutive right angle brackets (use '> >') int slidingPuzzle(vector<vector<int>>& board) { ^~ > > ...
解决方法
1. 编译时显式指定C++标准版本
在clang编译命令中添加-std参数,指定C11或更高版本(C++11及以后标准支持连续右尖括号的写法)。示例命令:
# 指定C++11标准 clang++ -std=c++11 main.cpp -o sliding_puzzle # 或指定更高版本,如C++14/C++17 clang++ -std=c++14 main.cpp -o sliding_puzzle clang++ -std=c++17 main.cpp -o sliding_puzzle
若需启用最新实验性特性,可指定-std=c++20或更高版本,必要时配合-stdlib=libc++参数。
2. 设置环境变量实现永久生效
如果希望每次编译都默认使用指定的C++标准,可通过设置环境变量实现:
- 临时生效(重启终端后失效):在Bash/Zsh中执行
export CXXFLAGS="-std=c++11" - 永久生效:将上述命令添加到
~/.bashrc或~/.zshrc配置文件中,保存后执行source ~/.bashrc(对应配置文件)使更改立即生效。
额外提示
代码中存在一处逻辑错误:嵌套循环的内层循环条件i < cols应为j < cols,否则会触发死循环,建议修正后再编译运行。
内容的提问来源于stack exchange,提问作者Daesar Lau
相关产品推荐
相关产品推荐

