IAR 无法在启用自动(基于扩展)选项的情况下正确编译 C++ 文件

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

这可能有点远...

我有一个 C 项目并想包含一个 C++ 文件,但是我收到以下代码的错误:

//GPIO_CPP.cpp

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

#ifndef __cplusplus
    #error  Enable CPP compilation
#endif

这个包含在我的main.c如下:

//main.c

#include "GPIO_CPP.cpp"

错误:

Error[Pe020]: identifier "class" is undefined

我也试过将其放入具有相同行为的 .h 和 .hpp 扩展名的头文件中。

我已经进行了编译器检查:

#ifndef __cplusplus
    #error  Enable CPP compilation
#endif

正在开火。

我的编译器选项:

假设您正在尝试在 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);
}

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
}

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