首页 > 解决方案 > 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

标签: c++ccompiler-errorsiar

解决方案


假设您尝试在 C 项目中包含 C++ 模块,最好的方法是:

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);
}

主程序

#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
}

main.c将和添加gpio.cpp到您的项目树中,并确保将语言设置设置为Auto.


推荐阅读