c++ - 使用 GCC 编译 C++ 程序

标签 c++ gcc g++ gnu

如何使用 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++ 程序吗? 在相关说明中,gccg++ 之间有什么区别?

最佳答案

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/

相关文章:

c++ - MFC 文件创建不能与 pugixml 一起正常工作

C++ - 通过模板类进行模板特化

c++ - CUDA 中的并行批处理小矩阵不适用于 for 循环

c++ - 使用 libvlc 的段错误

c - 解释将Float转换为整数时的输出?

eclipse - 如何配置 Eclipse、GCC 和 OpenOCD 以与 STM32F4Discovery 板一起使用?

c - 将变量存储在 ELF 部分,稍后对其进行迭代

linux - 如何在 qmake 中设置库顺序?

c++ - 使用依赖项编译 PIN 工具

c++ - 模板中的关键字 "typename"