C++ Debug builds broke in Snow Leopard Xcode

cgccmacosxcode

After upgrading to Xcode 3.2 and Snow Leopard, my debug builds are broken and fail at runtime. Stringstreams do not seem to work. They work in Release mode.

I've narrowed it down to a combination of GCC 4.2, OSX SDK 10.6 and the _GLIBCXX_DEBUG pre-processor symbol. These are the defaults for new Xcode projects' Debug configurations.

This code shows the problem:

#include <iostream>
#include <string>
#include <sstream>

int main (int argc, char * const argv[]) {

    std::stringstream stream;
    std::cout << "             expected  actual" << std::endl;
    std::cout << "stream.bad:  0         " << stream.bad() << std::endl;
    std::cout << "stream.fail: 0         " << stream.fail() << std::endl;
    std::cout << "stream.eof:  0         " << stream.eof() << std::endl;
    std::cout << "stream.good: 1         " << stream.good() << std::endl;

    stream.exceptions(std::ios::badbit | std::ios::failbit | std::ios::eofbit);
    try{
        stream << 11;       //< Does not work as expected (see output)
    }catch (std::bad_cast &e) {
        std::cout << "Unexpected bad_cast: " << e.what() << std::endl;
    }catch(std::exception &e){
        std::cout << "Unexpected exception: " << e.what() << std::endl;
    }

    std::cout << "             expected  actual" << std::endl;
    std::cout << "stream.bad:  0         " << stream.bad() << std::endl;
    std::cout << "stream.fail: 0         " << stream.fail() << std::endl;
    std::cout << "stream.eof:  0         " << stream.eof() << std::endl;
    std::cout << "stream.good: 1         " << stream.good() << std::endl;
    std::cout << std::endl;
    std::cout << "EXPECT: " << 11 << std::endl;
    std::cout << "ACTUAL: " << stream.str() << std::endl;

    std::cout << std::endl << "Done" << std::endl;
    return 0;
}

The stringstream insertion should work, but when using GCC 4.2 and _GLIBCXX_DEBUG, the '<<' operator throws an exception, and the bad and fail bits are set.

I've tried various combinations of compiler and SDK with these results:
– Using GCC 4.2, LLVM-GCC, or CLANG with SDK 10.6 does NOT work.
– Using GCC 4.2, LLVM-GCC, or CLANG with SDK 10.5 does work.
– Using GCC 4.0 with either SDK 10.5 or 10.6 works.

If _GLIBCXX_DEBUG is broken or not supported (with SDK 10.6 and GCC 4.2), then why is this the default for Debug configurations in new projects (C++ command line)?

Best Answer

STL debug mode is not supported in gcc 4.2 at this time. You can use gcc 4.0 with STL debug mode, or remove the debug mode preprocessor macros from your Debug configuration and keep using gcc 4.2.