c++perlperl-xs

How to portably detect whether a compiler supports <iostream> vs <iostream.h>


I'm working on a utility that needs to be able to compile on both standard C++ compilers and pre-standard compilers. The code can and will be thrown at just about any C++ compiler in existence.

I am looking for a means to robustly and portably determine whether the target compiler supports header files with or without an .h extension. I will also need to detect whether namespaces are supported. Both of these needs may or may not be possible.

A little background: The utility is the Inline::CPP language extension for Perl. The extension automatically includes <iostream>, and tries to make a good guess whether a '.h' is required or not (and of course whether or not the compiler supports namespaces). But it's far from perfect in that regard, and this issue is diminishing the breadth of the utility's usefulness.

So to reiterate the question: How do I portably detect whether a compiler supports standard headers such as <iostream>, or pre-standard headers such as <iostream.h>?


Solution

  • Not in the code, but in the build/configure system. For example in CMake, you could use try_compile and provide it a sample file.

    ...
    try_compile(PRE_STANDARD_HEADERS tmp_builds pre_standard_headers_test.cpp)
    if ( ${PRE_STANDARD_HEADERS} )
        add_definitions( -D PRE_STANDARD_HEADERS )
    endif()
    

    You'd need to make that pre_standard_headers_test.cpp .. just a simple compilable exe that #include <iostream.h> for example.

    Then in your normal code just an

    #ifdef PRE_STANDARD_HEADERS
    

    would do the trick.