有一个 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
正确选择了正确的编译器,但随后使用了错误的链接器。这样对吗? 正如我所见(如果错了请纠正我)
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/