问题描述
问题:如何用gcc编译器编译C++程序?
Question: How to compile a C++ program with gcc compiler?
信息.c:
#include<iostream>
using std::cout;
using std::endl;
int main()
{
#ifdef __cplusplus
cout << "C++ compiler in use and version is " << __cplusplus << endl;
#endif
cout <<"Version is " << __STDC_VERSION__ << endl;
cout << "Hi" << __FILE__ << __LINE__ << endl;
}
当我尝试编译 info.c
$ gcc info.C
Undefined first referenced
symbol in file
cout /var/tmp/ccPxLN2a.o
endl(ostream &) /var/tmp/ccPxLN2a.o
ostream::operator<<(ostream &(*)(ostream &))/var/tmp/ccPxLN2a.o
ostream::operator<<(int) /var/tmp/ccPxLN2a.o
ostream::operator<<(long) /var/tmp/ccPxLN2a.o
ostream::operator<<(char const *) /var/tmp/ccPxLN2a.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
gcc 编译器不能编译 C++ 程序吗?在相关说明中,gcc 和 g++ 之间有什么区别.谢谢,
推荐答案
gcc 实际上可以很好地编译 C++ 代码.您收到的错误是链接器错误,而不是编译器错误.
gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.
如果你把编译行改成这样:
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
这使它链接到标准的 C++ 库,然后它就可以正常工作了.
which makes it link to the standard c++ library, then it will work just fine.
然而,你应该让你的生活更轻松并使用 g++.
However, you should just make your life easier and use g++.
Rup 在 他对另一个答案的评论:
[...] gcc 将选择正确的后端编译器基于文件扩展名(即将将 .c 编译为 C,将 .cc 编译为 C++)并将二进制文件链接到标准 C 和 GCC 帮助程序库由默认与输入语言无关;g++ 也会选择正确的后端基于扩展,除了我认为它编译了所有 C 源代码作为 C++ 代替(即它同时编译.c 和 .cc 作为 C++),它包括无论如何,libstdc++ 在其链接步骤中输入语言.
[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.
这篇关于使用 gcc 编译 C++ 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!