Why gcc and g++ Behave Differently: A Practical Guide to Compiling C and C++ with GCC
This tutorial explains how GCC version 10.2 compiles C and C++ programs, clarifies the differences between the gcc and g++ commands, shows how file extensions and the -x option affect language selection, and provides concrete command examples for successful compilation and linking.
GCC and G++ overview
GCC 10.2 (released September 2020) supports many languages; this guide focuses on compiling C and C++ source files.
Driver programs
Both gcc and g++ are front‑ends to the same compiler suite. By default they infer the language from the file extension. The -x option forces a specific language, e.g. gcc -xc file.c or gcc -xc++ file.cpp.
xxx.c → compiled as C
xxx.cpp → compiled as C++
xxx.m → compiled as Objective‑C
xxx.go → compiled as Go
Difference when compiling C code
Example C source (demo.c):
#include <stdio.h>
int main(){
const char *a = "abc";
printStr(a);
return 0;
}
int printStr(const char* str){
printf(str);
}Compiling with gcc -xc demo.c succeeds, while g++ demo.c reports errors because the C++ front‑end applies stricter language rules.
Compiling C++ code
Example C++ source (demo.cpp):
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "C语言中文网";
cout << str << endl;
return 0;
}Using g++ demo.cpp automatically links the C++ standard library and builds without errors.
Using gcc demo.cpp fails with undefined references (e.g., std::allocator) because gcc does not link -lstdc++ by default.
Compiling C++ with gcc
To compile C++ source with gcc, explicitly request C++ mode and link the C++ runtime:
gcc -xc++ -lstdc++ -shared-libgcc demo.cppThis command is functionally equivalent to g++ demo.cpp.
Practical recommendation
Use gcc for pure C programs.
Use g++ for C++ programs.
If gcc must be used for C++, add -xc++ -lstdc++ -shared-libgcc (or at least -lstdc++) to obtain the same behavior as g++.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
