When to Use gcc vs g++: Key Differences and Compilation Tips
This guide explains the GCC compiler's evolution, how to compile C and C++ programs using gcc and g++, highlights their differences, and provides practical command examples and linking options for successful builds.
Source: C Language Chinese Network; Edited by strongerHuang
As of September 2020, the GCC compiler has reached version 10.2 and can compile many languages, including C, C++, Go, Objective‑C, Fortran, Ada, D, and more. This tutorial focuses on compiling C and C++ programs.
To compile a C program, use the gcc command; for C++ programs, use g++. Although gcc can also compile C++ code, and g++ can compile C code, they differ in default behavior based on file extensions.
Files ending with .c are compiled as C by default.
Files ending with .cpp are compiled as C++ by default.
Files ending with .m are compiled as Objective‑C.
Files ending with .go are compiled as Go.
You can manually specify the language with the -x option, e.g., gcc -xc demo.c for C or gcc -xc++ demo.cpp for C++.
When using g++, the compiler always treats the source as C++ regardless of the file extension. This leads to stricter syntax checking compared to gcc. For example, the following C code compiles with gcc but produces errors with g++:
// demo.c
#include <stdio.h>
int main() {
const char *a = "abc";
printStr(a);
return;
}
int printStr(const char* str) {
printf(str);
}Compiling with gcc -xc demo.c succeeds, while g++ demo.c reports three errors because C++ enforces stricter standards.
Conversely, compiling a simple C++ program that uses the standard library with gcc fails to link the required libraries:
// demo.cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "C语言中文网";
cout << str << endl;
return 0;
}Running g++ demo.cpp succeeds, but gcc demo.cpp yields undefined reference errors. To compile C++ code with gcc, add the standard C++ library explicitly: gcc -xc++ -lstdc++ -shared-libgcc demo.cpp.
Thus, g++ is effectively equivalent to gcc -xc++ -lstdc++ -shared-libgcc, offering a convenient shortcut.
In summary, use gcc for C programs and g++ for C++ programs to avoid language‑specific issues and linking problems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
