Including C headers in a C++ namespace - is it a standard behavior?

c, c++

Solution

You may even do strange things like

//test.c
int
    #include "main.h"
{
    return 1;
}

//main.h
main(void)

The preprocessor macros are expanded before any syntax check is done. The above example will expand to

int
main(void)
{
    return 1;
}

which is legal code. While you really should avoid such examples, there are cases, where including into another element is quite useful. In your question it depends on how the names are mangled during compilation. If all the definitions in your header file are declared with `extern "C"`, the names will be searched unmangled in the object file, this is, however, not the case if the object file containing the implementation does not use the same namespace as it's definition in the consuming code and does not declare it `extern "C"`.

Problem

I have been believed that C header files must be included in the top level of C++ program. Anyway, I accidentally discovered that C++ is allowing inclusion of C headers in a sub namespace. ``` namespace AAA { extern "C" { #include "sqlite3.h" // C API. } } ``` And then, all the C types and functions will be placed in the namespace. More interestingly, all the linked C functions are also just working! I also discovered that this may cause some preprocessor issue, but except that, it seems to be working pretty fine. Is this a standard behavior? (I am using Clang 3.x) If it is, what is the name of this feature and where can I find this feature mentioned in the standard?

Original source