Mixing C++ and C Code; the define __cplusplus

  • Hi,

    I'm working on a project which is mixing C++ and C code. The modules communicate with each other by function calls. Therefore I'm using extern "C" {} within the cpp header files and including c header files within the brackets which works great.

    Now I'm facing the following problem:

    Within cpp files __cplusplus is defined. The following code:
    #ifdef __cplusplus
    #error __cplusplus is defined!
    #error __cplusplus is not defined!

    puts out: __cplusplus is defined!

    But within c files __cplusplus is not defined.
    The code above puts out: __cplusplus is not defined!

    I would like to have __cplusplus also defined for the precompilation of the c code files because I need to hide some #pragma instructions which cannot be processed by the c++ compiler.

    Any ideas?

  • Moderators

    by default most compilers are guessing they C/C++ compile mode by the file extension.
    So they are also providing compiler specific flags to force them into a specific mode.

    e.g. for "MSVC ":https://msdn.microsoft.com/en-us/library/032xwy55.aspxcompilers

    Is the C lib under your control or is it a 3rd party library?

  • Okay, so it seems that in my case the compiler/precompiler determines depending on the file extension (.c/.cpp) which language is used and therefore defines __cplusplus or not.

    I'm using Qt 5.3.2 with MinGW (so it's the GCC). I will look for the flags you mentioned.


    The C lib is partly under my control, this means I want to change as less as possible and the __cplusplus define seems to be a good compromise. If it's possible I would like to stick to it. Instead of creating a own define like __cplusplus1 or smth else

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.