开发者

Why gcc can compile C++ code but can not link?

开发者 https://www.devze.com 2022-12-22 01:26 出处:网络
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 so开发者_如何学Gource.

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 so开发者_如何学Gource.

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


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


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.


You can link with -lstdc++.

0

精彩评论

暂无评论...
验证码 换一张
取 消