14

There's a C++ code:

#include <stdio.h>

int main() {

int b = sizeof('a');
if(b==4) printf("I'm a C program!\n");
else printf("I'm a C++ program!\n");
}

Compile it like this:

gcc main.cpp -o main

It succeeds and gives:

I'm a C++ program!

Then add a line somewhere inside function main

int *p1 = new int [1000];

It fails with:

C:\Users\...\AppData\Local\Temp\cccJZ8kN.o:main1.cpp:(.text+0x1f): undefined reference to operator new[](unsigned long long)'
collect2.exe: error: ld returned 1 exit status

Then the following two commands successfully compile the code:

gcc main.cpp -o main -lstdc++

and

g++ main.cpp -o main

The compiler is minGW-win64 (http://mingw-w64.sourceforge.net/).

The questions are:

  1. Which of the two last commands are better?
  2. To my mind gcc correctly chooses the right compiler but then uses a wrong linker. Is it right?
  3. May it be a problem in minGW-win64?

As I see (correct me if it's wrong) gcc was intended to be a main program that takes the input and decides what to do with it. So I'd better use gcc if it worked without -lstdc++. But if it's not possible I'll prefer using g++ instead as don't know what else gcc may miss.

Many thanks for your considerations

Nick Legend
  • 789
  • 1
  • 7
  • 21
  • 2
    `gcc` is for C, `g++` is for C++. `gcc -lstdc++` might work for C++, but you really should just be using `g++` for C++. – Cornstalks Dec 09 '14 at 22:39
  • As an aside, a C++ program has `sizeof 'A' == 1`, while a C program has `sizeof 'A' == sizeof(int)`. On some implementations, both are true at the same time either way. – Deduplicator Dec 09 '14 at 22:47
  • See also http://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc – nos Dec 09 '14 at 22:49
  • Thanks for your answers, guys! As I see it must be expected behavior of minGW-win64. Will choose `g++` for now. – Nick Legend Dec 10 '14 at 09:11

1 Answers1

23

gcc is the GCC compiler-driver for C programs, g++ is the one for C++ programs.
Both will guess the language on the basis of the file-extension, unless overridden.

But if you use the wrong driver, the default-options will be wrong, like leaving out the C++ standard-library for C++ programs compiled with gcc when linking.

You can add just the library with -lstdc++, though using the proper driver is preferable, as plain gcc may be missing other, subtler options.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
Deduplicator
  • 44,692
  • 7
  • 66
  • 118