问题:如何使用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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译 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
Run Code Online (Sandbox Code Playgroud)
gcc编译器不能编译C++程序吗?在相关的说明中,gcc和g ++之间有什么区别.谢谢,
Eva*_*ran 115
gcc实际上可以很好地编译c ++代码.您收到的错误是链接器错误,而不是编译器错误.
可能的情况是,如果您将编译行更改为:
gcc info.C -lstdc++
Run Code Online (Sandbox Code Playgroud)
这使它链接到标准的c ++库,然后它将工作得很好.
但是,你应该让你的生活更轻松,并使用g ++.
编辑:
[...] gcc将根据文件扩展名选择正确的后端编译器(即将.c编译为C,将.cc编译为C++)并默认将二进制文件与标准C和GCC帮助程序库相链接,而不管输入语言; g ++还将基于扩展选择正确的后端,除了我认为它将所有C源代码编译为C++(即它将.c和.cc编译为C++),并且无论输入语言如何,它在链接步骤中都包含libstdc ++.
小智 41
如果你给代码一个.c扩展名,编译器认为它是C代码,而不是C++.C++编译器驱动程序称为g ++,如果使用gcc驱动程序,则会出现链接器问题,因为默认情况下标准C++库不会链接.所以你要:
g++ myprog.cpp
Run Code Online (Sandbox Code Playgroud)
甚至不要考虑使用大写的.C扩展名,除非你永远不想移植你的代码,并准备好被你工作的人讨厌.
Pra*_*n S 11
gcc和g ++之间的区别是:
gcc | g++
compiles c source | compiles c++ source
Run Code Online (Sandbox Code Playgroud)
使用g ++而不是gcc来编译c ++源代码.
默认情况下,gcc根据文件扩展名选择语言,但您可以强制gcc使用-x选项选择不同的语言后端:
gcc -x c++
Run Code Online (Sandbox Code Playgroud)
更多选项在gcc手册页的"选项控制输出类型"下详细说明.参见例如http://linux.die.net/man/1/gcc(在页面上搜索文本-x language).
在gcc无法使用文件扩展名猜测语言的情况下,此工具非常有用,例如,如果您生成代码并通过stdin将其提供给gcc.