tags:

views:

100

answers:

4

I know that c++ code should be compiled and linked by g++, not gcc. But why gcc can still compile c++ source code in spite of lots of c++ keywords in the source.

By the way, I found that I even can build a shared library by gcc with all c++ code. Why?

+8  A: 

g++ is gcc, it just automatically links to the standard C++ libraries.

If your g++ code depends on the standard libraries (things in the std namespace), you can

  1. use the g++ command, and its all automatic
  2. use gcc command, and specify the C++ standard libraries explicitly (-lstdc++)
Will
+1  A: 

You can link with -lstdc++.

Tronic
doesn't work. tons of errors when I link
solotim
@solotim, it does work. Maybe you're missnig something? Or perhaps you should edit your question, and specify the errors.
Pavel Shved
A: 

Are you referring to the GCC: The GNU C Compiler or GCC: The GNU Compiler Collection? If the former, than nothing C++ should be accepted -- the compiler will choke on it if I'm not mistaken. If the latter, running, say gcc something.cpp will route your code to the correct compiler in the collection to handle it -- in this case, g++. By calling g++ directly you're simply skipping that redirection step.

Billy ONeal
+2  A: 

From the GCC manpage:

   For any given input file, the file name suffix determines what kind of
   compilation is done:

   file.c
       C source code which must be preprocessed.

   .
   .
   .

   file.h
       C, C++, Objective-C or Objective-C++ header file to be turned into
       a precompiled header.

   file.cc
   file.cp
   file.cxx
   file.cpp
   file.CPP
   file.c++
   file.C
       C++ source code which must be preprocessed.  Note that in .cxx, the
       last two letters must both be literally x.  Likewise, .C refers to
       a literal capital C.

What it doesn't do is automatically link to the C++ standard libraries. It's easiest just to use g++ at that point.

Xorlev
If you're going to downrate, comment.
Xorlev