Compiling a C++ program with gcc

2019-01-04 08:45发布

Question: How to compile a C++ program with gcc compiler?

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;
}

and when I try to compile 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

Isn't gcc compiler capable of compiling C++ programs? On a related note, what is the difference between gcc and g++. Thanks,

标签: c++ gcc g++ gnu
7条回答
对你真心纯属浪费
2楼-- · 2019-01-04 09:27

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++

which makes it link to the standard c++ library, then it will work just fine.

However, you should just make your life easier and use g++.


EDIT:

Rup says it best in his comment to another answer:

[...] 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.

查看更多
登录 后发表回答