使用gcc -lstdc++编译C++文件时,如何查看所用C++版本?
Great question! When you're compiling C++ code with gcc -g test.cpp -lstdc++ -o out, figuring out which C++ standard is being used is super useful—here are a few reliable ways to do it:
1. Check GCC's default C++ standard based on its version
First, find out your GCC version by running:
gcc --version
GCC uses different default C++ standards depending on its release. Here's a quick breakdown of the defaults:
- GCC 4.7 or older: Defaults to C++98
- GCC 4.8–4.9: Defaults to C++11
- GCC 5–6: Defaults to C++14
- GCC 7–10: Defaults to C++17
- GCC 11 and newer: Defaults to C++20
If you aren't adding any -std= flags to your compile command, this is the standard you're using.
2. Use verbose output to see the exact standard during compilation
Add the -v flag to your compile command to get detailed build logs:
gcc -g test.cpp -lstdc++ -o out -v
Scroll through the output and look for a line starting with something like -std=gnu++xx—the xx here indicates the version (the gnu prefix means it's using GNU extensions alongside the standard C++ version). For example, -std=gnu++17 means you're using C++17 with GNU-specific additions.
3. Detect the version directly in your code
This is probably the most straightforward method—add a small snippet to your test.cpp to print the C++ standard being used:
#include <iostream> int main() { #if __cplusplus == 202002L std::cout << "Using C++20" << std::endl; #elif __cplusplus == 201703L std::cout << "Using C++17" << std::endl; #elif __cplusplus == 201402L std::cout << "Using C++14" << std::endl; #elif __cplusplus == 201103L std::cout << "Using C++11" << std::endl; #elif __cplusplus == 199711L std::cout << "Using C++98" << std::endl; #else std::cout << "Unknown C++ version" << std::endl; #endif return 0; }
Compile and run the program, and it'll directly tell you which standard is in use. This works because the __cplusplus macro is defined by the compiler to match the current C++ standard version.
Bonus: How to manually specify a C++ version
If you want to override the default, just add the -std=c++xx flag to your command. For example:
- Use pure C++17:
gcc -g test.cpp -lstdc++ -o out -std=c++17 - Use C++20 with GNU extensions:
gcc -g test.cpp -lstdc++ -o out -std=gnu++20
内容的提问来源于stack exchange,提问作者xksyvone

