Compiling a C++ program with GCC

c++, g++, gcc, gnu

Solution

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

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.

Problem

How can I compile a C++ program with the GCC compiler? File 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 the GCC compiler capable of compiling C++ programs? On a related note, what is the difference between `gcc` and `g++`?

Original source

Related problems