c++ - gcc 编译 C++ 代码 : undefined reference to `operator new[](unsigned long long)'

标签 c++ gcc g++

有一个 C++ 代码:

#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");
}

像这样编译它:
gcc main.cpp -o main

它成功并给出:
I'm a C++ program!

然后在函数内部的某处添加一行 main
int *p1 = new int [1000];

它失败了:
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

然后下面两条命令就成功编译了代码:
gcc main.cpp -o main -lstdc++


g++ main.cpp -o main

编译器是 minGW-win64 ( http://mingw-w64.sourceforge.net/ )。

问题是:
  • 最后两个命令哪个更好?
  • 在我看来 gcc正确选择了正确的编译器,但随后使用了错误的链接器。这样对吗?
  • 可能是 minGW-win64 的问题吗?

  • 正如我所见(如果错了请纠正我)gcc旨在成为一个主程序,它接受输入并决定如何处理它。所以我最好用gcc如果没有 -lstdc++ 也能工作.但如果不可能,我会更喜欢使用 g++相反,因为不知道还有什么 gcc可能会错过。

    非常感谢您的考虑

    最佳答案

    gcc is the GCC compiler-driver for C programs, g++ is the one for C++ programs.
    除非被覆盖,否则两者都会根据文件扩展名猜测语言。

    但是如果你使用了错误的驱动程序,默认选项就会出错,比如忽略了使用 gcc 编译的 C++ 程序的 C++ 标准库。链接时。

    您可以使用 -lstdc++ 添加库,但最好使用适当的驱动程序,如普通的 gcc may be missing other, subtler options .

    关于c++ - gcc 编译 C++ 代码 : undefined reference to `operator new[](unsigned long long)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50746894/

    相关文章:

    c++ - 如何确定我的程序还剩多少虚拟内存?

    c++ - 'to_string' 不是 'std' 的成员

    c++ - GCC 模板推导消除 const 错误?

    c - Tint2 编译

    linux - 使用命令行编译 C++ 代码

    c++字符串容量在复制分配期间发生变化

    c++ - 从文件读取到 C++ 中的数据结构

    C++ 在模板编译器错误中使用模板

    使用 gcc 的 c++ 命令行编译

    c++ - 段错误位置因printf而不同