Gcc C ++ code compilation: undefined reference to `operator new [] (unsigned long long) '

There 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 as follows:

 gcc main.cpp -o main 

It succeeds and gives:

 I'm a C++ program! 

Then add a line somewhere inside the main function

 int *p1 = new int [1000]; 

Failure:

 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/ ).

Questions:

  • Which of the last two teams is better?
  • In my opinion, gcc selects the correct compiler correctly, but then uses the wrong linker. Is it right?
  • Maybe the problem is in minGW-win64?

As I see it (correct me if it is wrong) gcc was supposed to be the main program that takes the input information and decides what to do with it. Therefore, I would rather use gcc if it worked without -lstdc++ . But if this is not possible, I prefer to use g++ , and I don’t know what else gcc can do.

Thanks so much for your thoughts.

+6
source share
1 answer

gcc is a GCC compiler for C programs, g++ is one for C ++ programs.
Both will guess the language based on the file extension, if not overridden.

But if you use the wrong driver, the default parameters will be incorrect, for example, if you do not use the standard C ++ library for C ++ programs compiled with gcc .

You can only add a library using -lstdc++ , although it is preferable to use the correct driver.

+11
source

Source: https://habr.com/ru/post/979368/


All Articles