iglesias iglesias - 3 months ago 24
C++ Question

Same STL files with different compilers

There are two binary files obtained from the same source file: one compiled with clang++-3.6 and the other one with g++-4.8. In a call to a function from the stl (std::unique, in particular) gdb brings me to the same file: /usr/include/c++/4.8/bits/stl_algo.h.

I expected that the implementations would be different for each compiler though. Do clang and gcc share parts of their C++ implementations?

Answer

I expected that the implementations would be different for each compiler though. Do clang and gcc share parts of their C++ implementations?

It's not that they share the same C++ implementations, it is rather that both compilers link with the same standard c++ library by default on your system.

I presume you are on linux, almost all programs installed from package manager link against libstdc++ (provided by g++).

By default, even when compiling with clang++, libstdc++ is used, so when you include iostream for example, it uses the one from /usr/include/c++/4.8.

If you want to link against llvm c++ library, you need to install the "libc++-dev" package (name may vary depending on your distro) and compile using: -stdlib=libc++ (instead of the default: -stdlib=libstdc++).

example:

test.cpp:

    #include <iostream>

    int main(int argc, char *argv[])
    {
        std::cout << "Hello World!!!\n";

        return 0;
    }

compiling using:

   $ clang++ -stdlib=libc++ -o test test.cpp

will use the header from /usr/include/c++/v1 (from llvm)

but compiling using:

    $ clang++ -stdlib=libstdc++ -o test test.cpp

# or (assuming the default on your system is libstdc++)

    $ clang++ -o test test.cpp

will use header from /usr/include/c++/4.8 (from g++)

Comments