gcc编译C ++代码:对`operator new [](unsigned long long)的未定义引用 [英] gcc compiling C++ code: undefined reference to `operator new[](unsigned long long)'
问题描述
有一个C ++代码:
#include< stdio.h>
int main(){
int b = sizeof(’a’);
if(b == 4)printf(我是C程序!\n);
else printf(我是C ++程序!\n);
}
像这样编译:
gcc main.cpp -o main
它成功并给出:
我是C ++程序!
然后在函数 main
内的某处添加一行
int * p1 = new int [1000];
失败的原因:
C:\Users\ ... \AppData\Local\Temp\cccJZ8kN.o:main1.cpp :(。text + 0x1f):未定义对运算符new的引用[] (unsigned long long)'
collect2.exe:错误:ld返回了1个退出状态
然后,以下两个命令成功编译了代码:
gcc main.cpp -o main -lstdc ++
和
g ++ main。 cpp -o main
编译器是minGW-win64( http://mingw-w64.sourceforge.net/ )。
问题是:
- 最后两个命令中哪个更好?
- 在我看来,
gcc
正确选择了正确的编译器,但随后使用了错误的链接器。是吗? - 在minGW-win64中可能会出现问题吗?
我请参阅(如果错了,请纠正我) gcc
旨在成为一个接受输入并决定如何处理输入的主程序。因此,如果没有 -lstdc ++
可以使用 gcc
。但是,如果不可能,我会更喜欢使用 g ++
,因为不知道还有什么 gcc
会丢失。 / p>
非常感谢您的考虑
gcc
是C程序的GCC编译器驱动程序, g ++
是用于C ++程序的语言。
除非被覆盖,否则两者都会根据文件扩展名猜测语言。
但是,如果使用错误的驱动程序,则默认选项将是错误的,例如在链接时忽略了用 gcc
编译的C ++程序的C ++标准库。
您可以仅添加带有 -lstdc ++
的库,尽管最好使用适当的驱动程序,因为普通gcc 可能缺少其他更精巧的选项。
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:
- Which of the two last commands are better?
- To my mind
gcc
correctly chooses the right compiler but then uses a wrong linker. Is it right? - 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
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.
这篇关于gcc编译C ++代码:对`operator new [](unsigned long long)的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!