如何使用 GCC 编译器编译 C++ 程序?
文件info.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 info.C -lstdc++
这使它链接到标准 C++ 库,然后它就可以正常工作了。
但是,您应该让您的生活更轻松并使用 g++
。
Rup his comment 中说得最好另一个答案:
[...] 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.
关于c++ - 使用 GCC 编译 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3178342/