Search code examples
c++ccompiler-errorsiar

IAR does not correctly compile C++ file with Auto (extension-based) option enabled


This may be a bit of a long shot...

I have a C project and want to include a C++ file however I am getting an error with the following code:

//GPIO_CPP.cpp

class GPIO
{
    public:
        uint32_t Port;
        uint32_t Pin;
};

#ifndef __cplusplus
    #error  Enable CPP compilation
#endif

This inluded in my main.c as follows:

//main.c

#include "GPIO_CPP.cpp"

Error:

Error[Pe020]: identifier "class" is undefined

I have also tried putting this in a header file with .h and .hpp extensions with the same behaviour.

I've placed a compiler check:

#ifndef __cplusplus
    #error  Enable CPP compilation
#endif

which is firing.

My compiler options:

Image of compiler setting


Solution

  • Assuming you are trying to include C++ module in C project, best way to do this is this:

    gpio.h

    #ifndef GPIO_H
    #define GPIO_H
    
    // Types accessible to C and C++ modules
    
    struct GPIO
    {
        uint32_t Port;
        uint32_t Pin;
    };
    
    // Functions accessible to C and C++ modules.
    // Use extern "C" only when included to C++ file.
    #ifdef __cplusplus
    extern "C" {
    #endif
    void foo(uint32_t x);
    #ifdef __cplusplus
    }
    #endif
    
    // Functions accessible to C++ modules only.
    // These functions not visible if included to C file.
    #ifdef __cplusplus
    void bar(uint32_t x);
    #endif
    
    #endif
    

    gpio.cpp

    #include "gpio.h"
    
    // extern "C" declaration must be visible to this definition to compile with C compatible signature
    void foo(uint32_t x) {
        // It's OK to call C++ functions from C compatible functions, 
        // because this is C++ compilation unit.
        bar(x);
    }
    
    // This function can be called only from C++ modules
    void bar(uint32_t x) {
        // It's OK to call C compatible functions from C++ functions
        foo(x);
    }
    

    main.c

    #include "gpio.h"
    
    // Use only C compatible types (struct GPIO) and functions (foo) here
    int main(void) {
        foo(1); // ok, because of extern "C"
        bar(1); // invalid because this is C file
    }
    

    Add main.c and gpio.cpp to your project tree, and make sure Language setting is set to Auto.