gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:17:16 26 4
gpt4 key购买 nike

这可能有点遥远......

我有一个 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

正在发射。

我的编译器选项:

Image of compiler setting

最佳答案

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

ma​​in.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 添加到您的项目树中,并确保语言设置设置为自动

关于c++ - 在启用自动(基于扩展)选项的情况下,IAR 无法正确编译 C++ 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58189276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com